Implement the ping protocol in C
By Ifeanyi Obi, Network Protocols Instructor
ping is usually the first network tool anyone learns, and it is also one of the best first protocol implementations to write. It is small enough to finish in an evening, but it touches everything that matters: binary message formats, byte order, checksums, raw sockets and timing.
How ping works
ping uses ICMP, the Internet Control Message Protocol (RFC 792). It sends an echo request, ICMP type 8, to a host. If the host is reachable and willing to answer, it sends back an echo reply, type 0, carrying the same identifier, sequence number and payload. Measure the time between the two and you have a round-trip time.
Every ICMP message carries a checksum: the one's-complement of the one's-complement sum of the message's 16-bit words (RFC 1071). It sounds complicated but it's a short loop, and a handy property is that a correct message, checksum included, sums to zero, which is how we check replies.
// ping.c: a minimal IPv4 ping using a raw ICMP socket.
// Build: cc -Wall -Wextra -O2 -o ping ping.c
// Run: sudo ./ping example.com (raw sockets need root or CAP_NET_RAW)
#include <arpa/inet.h>
#include <netdb.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#define ICMP_ECHO_REQUEST 8
#define ICMP_ECHO_REPLY 0
#define PAYLOAD_SIZE 56 // same default as the system ping
// ICMP echo message (RFC 792). Fields are big-endian on the wire.
struct icmp_echo {
uint8_t type;
uint8_t code;
uint16_t checksum;
uint16_t id;
uint16_t seq;
uint8_t payload[PAYLOAD_SIZE];
};
// Internet checksum (RFC 1071): one's-complement sum of 16-bit words.
static uint16_t checksum(const void *data, size_t len) {
const uint8_t *p = data;
uint32_t sum = 0;
while (len > 1) {
sum += (uint32_t)p[0] << 8 | p[1];
p += 2;
len -= 2;
}
if (len) sum += (uint32_t)p[0] << 8; // odd trailing byte
while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16); // fold carries
return (uint16_t)~sum;
}
static double now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
}Raw sockets
A normal TCP or UDP socket hides the protocol headers. To send ICMP we open a raw socket with socket(AF_INET, SOCK_RAW, IPPROTO_ICMP). The kernel still builds the IP header when we send, but it hands us the whole IP packet, header included, when we receive. Raw sockets need root or the CAP_NET_RAW capability, because a program that can write arbitrary packets can also forge them.
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s host\n", argv[0]);
return 2;
}
// 1. Resolve the host name to an IPv4 address.
struct addrinfo hints = {.ai_family = AF_INET}, *res;
int gai = getaddrinfo(argv[1], NULL, &hints, &res);
if (gai != 0) {
fprintf(stderr, "%s: %s\n", argv[1], gai_strerror(gai));
return 1;
}
struct sockaddr_in dst = *(struct sockaddr_in *)res->ai_addr;
freeaddrinfo(res);
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &dst.sin_addr, ip, sizeof ip);
// 2. Open a raw socket. The kernel adds the IP header for us when sending,
// but includes it in what we receive.
int fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (fd < 0) {
perror("socket (run as root or grant CAP_NET_RAW)");
return 1;
}
struct timeval timeout = {.tv_sec = 1};
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);
uint16_t id = (uint16_t)getpid();
int sent = 0, received = 0, count = 4;
printf("PING %s (%s): %d data bytes\n", argv[1], ip, PAYLOAD_SIZE);The send and receive loop
For each sequence number we fill in an echo request, store the send time in the payload, compute the checksum and send it. Then we read until our own reply arrives or the one-second receive timeout fires. Three details matter here:
- The reply starts with the IP header, whose length is in the low four bits of the first byte, counted in 32-bit words. Skip that many bytes to reach the ICMP message.
- A raw socket sees every ICMP packet reaching the host, including other programs' pings and, on loopback, our own request. Check the type, identifier and sequence number before trusting a packet.
- The TTL printed in the output is byte 8 of the IP header.
for (uint16_t seq = 1; seq <= count; seq++) {
// 3. Build an echo request. We put the send time in the payload so we can
// measure the round trip when it comes back.
struct icmp_echo req = {.type = ICMP_ECHO_REQUEST, .id = htons(id), .seq = htons(seq)};
double t0 = now_ms();
memcpy(req.payload, &t0, sizeof t0);
req.checksum = htons(checksum(&req, sizeof req));
if (sendto(fd, &req, sizeof req, 0, (struct sockaddr *)&dst, sizeof dst) < 0) {
perror("sendto");
break;
}
sent++;
// 4. Read until we get *our* reply or time out. A raw socket sees every
// ICMP packet for this host, including other programs' pings.
for (;;) {
uint8_t buf[1500];
struct sockaddr_in from;
socklen_t fromlen = sizeof from;
ssize_t n = recvfrom(fd, buf, sizeof buf, 0, (struct sockaddr *)&from, &fromlen);
if (n < 0) {
printf("Request timeout for icmp_seq %u\n", seq);
break;
}
size_t ihl = (size_t)(buf[0] & 0x0f) * 4; // IPv4 header length
if ((size_t)n < ihl + 8 + sizeof(double)) // IP header + ICMP header + timestamp
continue;
struct icmp_echo *rep = (struct icmp_echo *)(buf + ihl);
if (rep->type != ICMP_ECHO_REPLY || ntohs(rep->id) != id || ntohs(rep->seq) != seq)
continue; // not ours (or our own request echoed on loopback)
if (checksum(rep, (size_t)n - ihl) != 0)
continue; // corrupted
double t_sent;
memcpy(&t_sent, rep->payload, sizeof t_sent);
printf("%zd bytes from %s: icmp_seq=%u ttl=%u time=%.3f ms\n",
n - (ssize_t)ihl, inet_ntoa(from.sin_addr), seq, buf[8], now_ms() - t_sent);
received++;
break;
}
if (seq < count) sleep(1);
}
printf("--- %s ping statistics ---\n%d packets transmitted, %d received, %.0f%% packet loss\n",
argv[1], sent, received, sent ? 100.0 * (sent - received) / sent : 0.0);
close(fd);
return received > 0 ? 0 : 1;
}Build and run
$ cc -Wall -Wextra -O2 -o ping ping.c
$ sudo ./ping 127.0.0.1
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.037 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.042 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.054 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.042 ms
--- 127.0.0.1 ping statistics ---
4 packets transmitted, 4 received, 0% packet lossInstead of running it with sudo, you can grant just the one capability it needs: sudo setcap cap_net_raw+ep ./ping.
Ping without root
Linux also supports unprivileged ICMP sockets: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP). They only allow echo requests, the kernel manages the identifier for you, and replies arrive without the IP header. Which groups may use them is controlled by the net.ipv4.ping_group_range sysctl. Many distributions enable it, and it is one way the system ping can work without being setuid.
Exercises
- Add IPv6 support with ICMPv6 (echo request is type 128) and getaddrinfo with AF_UNSPEC.
- Print minimum, average and maximum round-trip times in the summary.
- Turn it into traceroute: send with increasing TTL values using setsockopt(IP_TTL) and listen for ICMP Time Exceeded messages.
In the next post we write the same program in Go and compare the two.