codelessgenie blog

Implementing Ping in C: A Comprehensive Guide

Ping is a fundamental network tool used to test reachability of a host on an IP network and measure round-trip time (RTT)—the time taken for a packet to travel from the source to the destination and back. At its core, Ping relies on the Internet Control Message Protocol (ICMP), a network layer protocol designed for error reporting and diagnostic purposes.

In this blog, we’ll explore how to implement a Ping utility from scratch in C. We’ll cover:

  • The ICMP protocol and packet structure.
  • Raw sockets (required for sending/receiving ICMP packets).
  • Checksum calculation, endianness, and RTT measurement.
  • Best practices for robustness, error handling, and security.
  • Advanced topics like IPv6 support and multithreading.

By the end, you’ll have a fully functional Ping tool and a deep understanding of its inner workings.

2026-06

Table of Contents#

  1. Introduction to Ping and ICMP
  2. Core Concepts for Ping in C
  3. Step-by-Step Implementation
  4. Common Practices and Best Practices
  5. Troubleshooting Common Issues
  6. Advanced Topics
  7. Testing and Debugging
  8. Complete Ping Program Example
  9. Conclusion
  10. References

1. Introduction to Ping and ICMP#

Ping works by sending an ICMP Echo Request (type 8) to a target host. If the host is reachable, it responds with an ICMP Echo Reply (type 0). The Ping utility:

  • Validates that the reply matches the request (using an identifier and sequence number).
  • Measures the time between sending the request and receiving the reply (RTT).
  • Reports statistics like packet loss and average latency.

Key ICMP Concepts#

  • Echo Request (Type 8): Sent by the Ping client to the target.
  • Echo Reply (Type 0): Sent by the target back to the client.
  • Identifier: Usually the client’s process ID (PID) to match replies to requests.
  • Sequence Number: Increments with each request to track packet order.
  • Checksum: Ensures the integrity of the ICMP packet (header + payload).

2. Core Concepts for Ping in C#

2.1. Raw Sockets#

ICMP is a network layer protocol (OSI Layer 3), which means we cannot use standard TCP/UDP sockets (transport layer, Layer 4) to send ICMP packets. Instead, we need raw sockets (SOCK_RAW), which allow direct access to the IP protocol stack.

Raw sockets require root privileges (or the CAP_NET_RAW capability) because they bypass the OS’s transport layer protections. You’ll need to run your Ping program with sudo.

2.2. ICMP Packet Structure#

An ICMP packet consists of a header followed by a payload. The header is defined in the netinet/icmp.h header file (Linux) as:

struct icmp {
    uint8_t  icmp_type;   // ICMP type (8 = Echo Request, 0 = Echo Reply)
    uint8_t  icmp_code;   // Subcode (always 0 for Echo Request/Reply)
    uint16_t icmp_cksum;  // Checksum (covers header + payload)
    union {
        struct {
            uint16_t id;   // Identifier (PID)
            uint16_t seq;  // Sequence number
        } echo;
        // Other fields for error messages (e.g., destination unreachable)
    } icmp_hun;
    uint8_t icmp_data[0]; // Payload (arbitrary data)
};
 
// Macros for easy access
#define icmp_id   icmp_hun.echo.id
#define icmp_seq  icmp_hun.echo.seq

For Ping, we use the echo sub-structure to store the identifier (PID) and sequence number. The payload can be any data (e.g., a timestamp for RTT calculation).

2.3. Checksum Calculation#

ICMP requires a 16-bit ones’ complement checksum over the entire packet (header + payload). The algorithm is:

  1. Sum all 16-bit words in the packet.
  2. If the total length is odd, pad the last byte with a zero.
  3. Fold carry-over bits (add the high 16 bits to the low 16 bits).
  4. Take the ones’ complement of the result.

Here’s a C implementation:

#include <stdint.h>
 
uint16_t icmp_checksum(const void *data, size_t length) {
    const uint16_t *buf = data;
    uint32_t sum = 0;
 
    // Sum all 16-bit words
    for (; length > 1; length -= 2) {
        sum += *buf++;
    }
 
    // Handle odd-length packets
    if (length == 1) {
        sum += *(const uint8_t *)buf;
    }
 
    // Fold carry-over bits
    sum = (sum >> 16) + (sum & 0xFFFF);
    sum += (sum >> 16); // Fold again if needed
 
    // Return ones' complement
    return (uint16_t)~sum;
}

2.4. Endianness Considerations#

Network protocols use big-endian (most significant byte first) byte order. For ICMP:

  • The icmp_cksum field is a 16-bit big-endian value.
  • The icmp_id and icmp_seq fields are opaque (the sender writes them in host byte order, and the receiver reads them in host byte order). No conversion is needed!

3. Step-by-Step Implementation#

3.1. Setup and Dependencies#

First, include the required headers:

#include <sys/socket.h>    // Sockets
#include <netinet/ip.h>    // IP header
#include <netinet/icmp.h>  // ICMP header
#include <arpa/inet.h>     // inet_pton(), inet_ntoa()
#include <unistd.h>        // sleep(), getpid()
#include <time.h>          // gettimeofday()
#include <string.h>        // memcpy(), memset()
#include <stdio.h>         // printf(), perror()
#include <stdlib.h>        // exit()
#include <errno.h>         // errno, strerror()

3.2. Creating a Raw Socket#

Raw sockets are created with socket() using AF_INET (IPv4), SOCK_RAW (raw mode), and IPPROTO_ICMP (ICMP protocol):

int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd == -1) {
    perror("socket() failed");
    exit(EXIT_FAILURE);
}

Set Receive Timeout#

To avoid hanging indefinitely, set a timeout for recvfrom() using setsockopt():

struct timeval timeout = {.tv_sec = 2, .tv_usec = 0}; // 2 seconds
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) {
    perror("setsockopt(SO_RCVTIMEO) failed");
    close(sockfd);
    exit(EXIT_FAILURE);
}

3.3. Constructing ICMP Echo Requests#

For each Ping, we build an ICMP Echo Request packet:

  1. Set the ICMP type to ICMP_ECHO (8).
  2. Set the identifier to the process ID (getpid()).
  3. Increment the sequence number.
  4. Add a payload (e.g., a timestamp for RTT).
  5. Calculate the checksum.

Example:

#define PAYLOAD_SIZE sizeof(struct timeval) // Use timestamp for RTT
 
void build_icmp_request(struct icmp *icmp_pkt, int seq) {
    memset(icmp_pkt, 0, sizeof(struct icmp) + PAYLOAD_SIZE);
 
    // ICMP header
    icmp_pkt->icmp_type = ICMP_ECHO;
    icmp_pkt->icmp_code = 0;
    icmp_pkt->icmp_id = getpid();
    icmp_pkt->icmp_seq = seq;
    icmp_pkt->icmp_cksum = 0;
 
    // Payload: current timestamp
    struct timeval send_time;
    gettimeofday(&send_time, NULL);
    memcpy(icmp_pkt->icmp_data, &send_time, PAYLOAD_SIZE);
 
    // Calculate checksum (header + payload)
    icmp_pkt->icmp_cksum = icmp_checksum(icmp_pkt, sizeof(struct icmp) + PAYLOAD_SIZE);
}

3.4. Sending Packets with sendto()#

Raw sockets use sendto() to send datagrams (since ICMP is connectionless). We specify the destination IP address using a struct sockaddr_in:

struct sockaddr_in dest_addr = {0};
dest_addr.sin_family = AF_INET;
 
// Convert IPv4 string to binary (e.g., "8.8.8.8" → 0x08080808)
if (inet_pton(AF_INET, "8.8.8.8", &dest_addr.sin_addr) != 1) {
    fprintf(stderr, "Invalid IPv4 address\n");
    exit(EXIT_FAILURE);
}
 
// Buffer for ICMP packet (header + payload)
char send_buf[sizeof(struct icmp) + PAYLOAD_SIZE];
struct icmp *icmp_pkt = (struct icmp *)send_buf;
 
// Build request (seq = 0, 1, 2, ...)
build_icmp_request(icmp_pkt, seq);
 
// Send packet
ssize_t sent = sendto(
    sockfd,          // Socket file descriptor
    send_buf,        // Packet buffer
    sizeof(send_buf),// Packet length
    0,               // Flags
    (struct sockaddr *)&dest_addr, // Destination address
    sizeof(dest_addr)
);
 
if (sent == -1) {
    perror("sendto() failed");
    close(sockfd);
    exit(EXIT_FAILURE);
}

3.5. Receiving and Processing Echo Replies#

Raw sockets return the entire IP packet (not just the ICMP payload). To process a reply:

  1. Read the IP header to find the ICMP payload.
  2. Validate the ICMP type (must be ICMP_ECHOREPLY = 0).
  3. Match the identifier (PID) and sequence number to the request.

Example:

#define RECV_BUF_SIZE 65536 // Max IP packet size (65535 bytes)
 
void process_reply(int sockfd, int expected_seq) {
    char recv_buf[RECV_BUF_SIZE];
    struct sockaddr_in src_addr;
    socklen_t src_addr_len = sizeof(src_addr);
 
    // Receive packet
    ssize_t recvd = recvfrom(
        sockfd,          // Socket
        recv_buf,        // Buffer
        RECV_BUF_SIZE,   // Buffer size
        0,               // Flags
        (struct sockaddr *)&src_addr, // Source address (reply sender)
        &src_addr_len
    );
 
    if (recvd == -1) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            printf("Request timed out\n");
        } else {
            perror("recvfrom() failed");
        }
        return;
    }
 
    // Parse IP header (first part of the buffer)
    struct ip *ip_hdr = (struct ip *)recv_buf;
    int ip_hdr_len = ip_hdr->ip_hl * 4; // ip_hl is 4-byte units
 
    // Validate IP protocol (must be ICMP)
    if (ip_hdr->ip_p != IPPROTO_ICMP) {
        fprintf(stderr, "Received non-ICMP packet\n");
        return;
    }
 
    // Parse ICMP header (after IP header)
    struct icmp *icmp_hdr = (struct icmp *)(recv_buf + ip_hdr_len);
 
    // Validate ICMP type (Echo Reply)
    if (icmp_hdr->icmp_type != ICMP_ECHOREPLY) {
        fprintf(stderr, "Received non-Echo Reply (type %d)\n", icmp_hdr->icmp_type);
        return;
    }
 
    // Validate identifier (matches our PID)
    if (icmp_hdr->icmp_id != getpid()) {
        fprintf(stderr, "Received reply for another process\n");
        return;
    }
 
    // Validate sequence number (matches expected)
    if (icmp_hdr->icmp_seq != expected_seq) {
        fprintf(stderr, "Received out-of-order reply (seq %d vs expected %d)\n",
                icmp_hdr->icmp_seq, expected_seq);
        return;
    }
 
    // Success! Process the reply (calculate RTT)
    calculate_rtt(icmp_hdr->icmp_data, ip_hdr->ip_ttl, src_addr);
}

3.6. Calculating Round-Trip Time (RTT)#

To measure RTT accurately, we include a timestamp in the ICMP payload. When we receive the reply, we subtract the payload timestamp from the current time:

#include <sys/time.h>
 
void calculate_rtt(const void *payload, int seq, int ttl, struct sockaddr_in src_addr) {
    // Extract payload timestamp (sent time)
    struct timeval send_time;
    memcpy(&send_time, payload, sizeof(send_time));
 
    // Get current time (receive time)
    struct timeval recv_time;
    gettimeofday(&recv_time, NULL);
 
    // Calculate RTT in microseconds
    long long rtt_us = (recv_time.tv_sec - send_time.tv_sec) * 1000000LL +
                       (recv_time.tv_usec - send_time.tv_usec);
    double rtt_ms = rtt_us / 1000.0;
 
    // Print results (like standard Ping)
    printf("%zd bytes from %s: icmp_seq=%d ttl=%d time=%.2f ms\n",
           sizeof(struct icmp) + PAYLOAD_SIZE,
           inet_ntoa(src_addr.sin_addr), // Source IP (reply sender)
           seq,                          // Sequence number
           ttl,                          // Time-to-Live (hops)
           rtt_ms);                      // RTT in milliseconds
}

4. Common Practices and Best Practices#

1. Always Check System Calls#

Every system call (e.g., socket(), sendto(), recvfrom()) can fail. Use perror() or strerror(errno) to report errors:

if (sendto(...) == -1) {
    perror("sendto() failed");
    close(sockfd);
    exit(EXIT_FAILURE);
}

2. Use Root Privileges Responsibly#

Raw sockets require CAP_NET_RAW (root). Warn users to run with sudo:

sudo ./ping 8.8.8.8

3. Validate Replies#

Always match replies to your requests using the identifier (PID) and sequence number. This ensures you don’t process replies meant for other Ping instances.

4. Include a Payload#

Adding a payload (e.g., a timestamp) improves RTT accuracy and helps detect packet corruption. Standard Ping uses a 56-byte payload (total packet size: 64 bytes).

5. Clean Up Resources#

Close the socket with close(sockfd) when done to avoid resource leaks.

6. Handle Signals#

Catch SIGINT (Ctrl+C) to exit gracefully and print statistics (packets sent/received/lost):

#include <signal.h>
 
int packets_sent = 0;
int packets_recv = 0;
 
void handle_sigint(int sig) {
    printf("\n--- Ping statistics ---\n");
    printf("%d packets transmitted, %d received, %.1f%% packet loss\n",
           packets_sent, packets_recv,
           (packets_sent - packets_recv) * 100.0 / packets_sent);
    close(sockfd);
    exit(EXIT_SUCCESS);
}
 
// Register signal handler
signal(SIGINT, handle_sigint);

5. Troubleshooting Common Issues#

IssueCauseSolution
socket() failed: Permission deniedNo root privilegesRun with sudo
Request timed outFirewall blocks ICMP, host unreachableDisable firewall/allow ICMP; check host
Checksum errorIncorrect checksum calculationEnsure checksum covers header + payload
Out-of-order repliesSequence number not tracked properlyIncrement seq after each request
Non-ICMP packet receivedRaw socket returns IP packetsValidate ip_hdr->ip_p == IPPROTO_ICMP

6. Advanced Topics#

6.1. IPv6 Support#

ICMPv6 (for IPv6) uses:

  • AF_INET6 (IPv6 address family).
  • IPPROTO_ICMPV6 (ICMPv6 protocol).
  • Echo Request (type 128), Echo Reply (type 129).
  • struct icmp6_hdr (ICMPv6 header).

Example socket creation:

int sockfd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);

6.2. Multithreaded Ping#

Use threads to send multiple Pings concurrently. For example, ping 10 hosts at once:

  • Use pthread_create() to spawn a thread per host.
  • Synchronize shared variables (e.g., packets_sent) with mutexes.

6.3. Rate Limiting#

Send one Ping per second using sleep(1) to avoid flooding the network (standard Ping behavior).

6.4. DNS Resolution with getaddrinfo()#

Use getaddrinfo() to resolve domain names (e.g., google.com) to IP addresses (supports IPv4/IPv6):

struct addrinfo hints = {0};
struct addrinfo *res;
 
hints.ai_family = AF_UNSPEC;   // Allow IPv4/IPv6
hints.ai_socktype = SOCK_RAW;
hints.ai_protocol = IPPROTO_ICMP; // Or IPPROTO_ICMPV6 for IPv6
 
int status = getaddrinfo("google.com", NULL, &hints, &res);
if (status != 0) {
    fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
    exit(EXIT_FAILURE);
}
 
// Use res->ai_addr for destination address

7. Testing and Debugging#

1. Wireshark#

Capture ICMP packets to verify their structure:

  • Filter: icmp (IPv4) or icmpv6 (IPv6).
  • Check: Source/Destination IP, ICMP type/code, identifier/sequence, checksum.

2. strace#

Trace system calls to debug socket issues:

strace ./ping 8.8.8.8

3. Print Debug Information#

Add printf() statements to log:

  • ICMP header fields (type, ID, sequence).
  • Checksum values.
  • RTT calculations.

8. Complete Ping Program Example#

Here’s a fully functional Ping implementation combining all the above concepts:

#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/icmp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <stdint.h>
 
#define PAYLOAD_SIZE sizeof(struct timeval)
#define RECV_BUF_SIZE 65536
 
int sockfd;
int packets_sent = 0;
int packets_recv = 0;
 
uint16_t icmp_checksum(const void *data, size_t length) {
    const uint16_t *buf = data;
    uint32_t sum = 0;
 
    for (; length > 1; length -= 2) {
        sum += *buf++;
    }
 
    if (length == 1) {
        sum += *(const uint8_t *)buf;
    }
 
    sum = (sum >> 16) + (sum & 0xFFFF);
    sum += (sum >> 16);
 
    return (uint16_t)~sum;
}
 
void build_icmp_request(struct icmp *icmp_pkt, int seq) {
    memset(icmp_pkt, 0, sizeof(struct icmp) + PAYLOAD_SIZE);
 
    icmp_pkt->icmp_type = ICMP_ECHO;
    icmp_pkt->icmp_code = 0;
    icmp_pkt->icmp_id = getpid();
    icmp_pkt->icmp_seq = seq;
    icmp_pkt->icmp_cksum = 0;
 
    struct timeval send_time;
    gettimeofday(&send_time, NULL);
    memcpy(icmp_pkt->icmp_data, &send_time, PAYLOAD_SIZE);
 
    icmp_pkt->icmp_cksum = icmp_checksum(icmp_pkt, sizeof(struct icmp) + PAYLOAD_SIZE);
}
 
void calculate_rtt(const void *payload, int seq, int ttl, struct sockaddr_in src_addr) {
    struct timeval send_time, recv_time;
    memcpy(&send_time, payload, sizeof(send_time));
    gettimeofday(&recv_time, NULL);
 
    long long rtt_us = (recv_time.tv_sec - send_time.tv_sec) * 1000000LL +
                       (recv_time.tv_usec - send_time.tv_usec);
    double rtt_ms = rtt_us / 1000.0;
 
    printf("%zd bytes from %s: icmp_seq=%d ttl=%d time=%.2f ms\n",
           sizeof(struct icmp) + PAYLOAD_SIZE,
           inet_ntoa(src_addr.sin_addr),
           seq,
           ttl,
           rtt_ms);
 
    packets_recv++;
}
 
void process_reply(int expected_seq) {
    char recv_buf[RECV_BUF_SIZE];
    struct sockaddr_in src_addr;
    socklen_t src_addr_len = sizeof(src_addr);
 
    ssize_t recvd = recvfrom(sockfd, recv_buf, RECV_BUF_SIZE, 0,
                             (struct sockaddr *)&src_addr, &src_addr_len);
    if (recvd == -1) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            printf("Request timed out.\n");
        } else {
            perror("recvfrom() failed");
        }
        return;
    }
 
    struct ip *ip_hdr = (struct ip *)recv_buf;
    int ip_hdr_len = ip_hdr->ip_hl * 4;
 
    if (ip_hdr->ip_p != IPPROTO_ICMP) {
        fprintf(stderr, "Received non-ICMP packet.\n");
        return;
    }
 
    struct icmp *icmp_hdr = (struct icmp *)(recv_buf + ip_hdr_len);
 
    if (icmp_hdr->icmp_type != ICMP_ECHOREPLY) {
        fprintf(stderr, "Received non-Echo Reply (type %d).\n", icmp_hdr->icmp_type);
        return;
    }
 
    if (icmp_hdr->icmp_id != getpid()) {
        fprintf(stderr, "Received reply for another process.\n");
        return;
    }
 
    if (icmp_hdr->icmp_seq != expected_seq) {
        fprintf(stderr, "Received out-of-order reply (seq %d vs expected %d).\n",
                icmp_hdr->icmp_seq, expected_seq);
        return;
    }
 
    calculate_rtt(icmp_hdr->icmp_data, icmp_hdr->icmp_seq, ip_hdr->ip_ttl, src_addr);
}
 
void handle_sigint(int sig) {
    printf("\n--- Ping statistics ---\n");
    printf("%d packets transmitted, %d received, %.1f%% packet loss\n",
           packets_sent, packets_recv,
           (packets_sent - packets_recv) * 100.0 / packets_sent);
    close(sockfd);
    exit(EXIT_SUCCESS);
}
 
int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <IPv4 address>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
 
    signal(SIGINT, handle_sigint);
 
    sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
    if (sockfd == -1) {
        perror("socket() failed");
        exit(EXIT_FAILURE);
    }
 
    struct timeval timeout = {.tv_sec = 2, .tv_usec = 0};
    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) {
        perror("setsockopt(SO_RCVTIMEO) failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    struct sockaddr_in dest_addr = {0};
    dest_addr.sin_family = AF_INET;
    if (inet_pton(AF_INET, argv[1], &dest_addr.sin_addr) != 1) {
        fprintf(stderr, "Invalid IPv4 address: %s\n", argv[1]);
        close(sockfd);
        exit(EXIT_FAILURE);
    }
 
    printf("PING %s (%s) %zu bytes of data.\n", argv[1], inet_ntoa(dest_addr.sin_addr),
           sizeof(struct icmp) + PAYLOAD_SIZE);
 
    int seq = 0;
    while (1) {
        char send_buf[sizeof(struct icmp) + PAYLOAD_SIZE];
        struct icmp *icmp_pkt = (struct icmp *)send_buf;
 
        build_icmp_request(icmp_pkt, seq);
 
        ssize_t sent = sendto(sockfd, send_buf, sizeof(send_buf), 0,
                              (struct sockaddr *)&dest_addr, sizeof(dest_addr));
        if (sent == -1) {
            perror("sendto() failed");
            close(sockfd);
            exit(EXIT_FAILURE);
        }
        packets_sent++;
 
        process_reply(seq);
 
        seq++;
        sleep(1);
    }
 
    close(sockfd);
    return 0;
}

To compile:

gcc -o ping ping.c

To run:

sudo ./ping 8.8.8.8

9. Conclusion#

Implementing Ping in C is a great way to learn about low-level network programming, ICMP, and raw sockets. We covered:

  • The ICMP protocol and packet structure.
  • Raw socket creation and configuration.
  • Checksum calculation and RTT measurement.
  • Best practices for robustness and security.
  • Advanced topics like IPv6 and multithreading.

The complete example provides a functional Ping tool that you can extend with features like IPv6 support, statistics, or multithreading. Experiment with the code and explore the references below to deepen your knowledge!

10. References#

  1. RFCs
    • RFC 792: ICMP Specification (IPv4).
    • RFC 4443: ICMPv6 Specification (IPv6).
  2. Man Pages
    • man 2 socket, man 2 sendto, man 2 recvfrom, man 3 inet_pton, man 3 getaddrinfo.
  3. Books
    • Unix Network Programming, Volume 1 by W. Richard Stevens (definitive guide to sockets).
  4. Tools

Happy Pinging! 🚀