cpp-icmplib is simple header-only cross-platform library, which allows performing system-like ping requests from C++ applications without need of using system "ping" command. As this library is socket-based, on most operating systems, it will require administrator privilages (root) to run.
icmplib delivers function Ping declared as:
PingResult Ping(const icmplib::AddressIP &target, unsigned timeout = 1000, uint16_t sequence = 1, uint8_t ttl = 255, uint16_t packet_size = ICMPLIB_PING_DATA_SIZE);
Notice:
target- Network address (may be created from std::string)timeout- Timeout in millisecondssequence- Sequence number to be sentttl- Time-to-live to be set for packetpacket_size- ICMP echo payload size in bytes (default: ICMPLIB_PING_DATA_SIZE = 64)
PingResult structure is declared as:
struct PingResult {
enum class ResponseType {
Success,
Unreachable,
TimeExceeded,
Timeout,
Unsupported,
Failure
} response;
double delay;
icmplib::AddressIP address;
uint8_t code;
uint8_t ttl;
};
Notice:
delay- Time in miliseconds between sending request and receiving responseaddress- Address of responding hostcode- ICMP Code parameterttl- Received IPv4 header TTL parameterresponse- Type of received response
ResponseType | Meaning
--------------------------------------------------------------------------------------------------------
Success | ICMP Echo Response successfully received
Unreachable | ICMP Destination Ureachable message received (eg. target host does not exist)
TimeExceeded | ICMP Time Exceeded message received (eg. TTL meet zero value on some host)
Timeout | No message recived in given time (see "timeout" parameter)
Unsupported | Received unsupported ICMP packet
Failure | Failed to send ICMP Echo Request to given target host
Packets that do not belong to the active ping request are ignored while waiting for the matching reply. This includes ICMP traffic for other hosts or other processes that may be visible on the raw socket, for example when a NIC is running in promiscuous mode.
In order to make internet connection test simply use:
#include "icmplib.h"
...
bool isConnected()
{
return icmplib::Ping("8.8.8.8", ICMPLIB_TIMEOUT_1S).response == icmplib::PingResponseType::Success; // Test Google DNS address
}
Simple traceroute implementation:
#include "icmplib.h"
#include <vector>
...
std::vector<std::string> traceroute(const std::string &address)
{
std::vector<std::string> result;
for (uint8_t ttl = 1; ttl != 0; ttl++) {
auto ping = icmplib::Ping(address, ICMPLIB_TIMEOUT_1S, 1, ttl);
switch (ping.response) {
case icmplib::PingResult::ResponseType::TimeExceeded:
result.push_back(ping.address.ToString());
break;
case icmplib::PingResult::ResponseType::Success:
result.push_back(ping.address.ToString());
return result;
default:
return result;
}
}
return result;
}
On Windows 10 ICMP messages other than Echo Response seem to be blocked and, while being received, are not passed to application via socket, timeout is detected instead