This sample C program demonstrates how an ICMP ping app can be written using the SOCK_RAW socket type and IPPROTO_ICMP protocol. ICMP or Internet Control Message Protocol is used by network devices to measure round-trip-delays and packet loss across network paths.

Ping is a necessary tool in any Operating System to debug the IP address of the network device to see if the device is reachable.

By creating a raw socket, the underlying layer does not change the protocol header. When we submit the ICMP header, nothing is adjusted so that the receiving end will see an ICMP packet. Additionally, we use the record route IP option to get a round trip path to the endpoint. Ping sends out ICMP packets by opening a RAW socket, which is separate from TCP and UDP.

Note that the size of the IP option header that records the route is limited to nine IP addresses.

ICMP Ping - C Implementation

Internet Control Message Protocol (ICMP) Ping – C Program

Compile the Ping program

This program is modified to work fine with Visual Studio in Windows 10. It compiles successfully both with 32 and 64 bit versions of the OS.

If you want to use Visual Studio Developer command line to compile the Ping program, use the following command. Read more about compiling C/C++ Program from command line here.

Run the Ping Program

This C Program has the following Command Line Options and Parameters.

Ping [host] [packet-size]

Host String name of host to ping

packet-size Integer size of packet to send (smaller than 1024 bytes)

You can use this program to ping internet addresses such as

Ping C Program Source Code

Below is the full source code you can use. Alternatively, you can download the complete Visual Studio 2017 C++ Solution file here:

  Ping C Program (7.1 KiB, 456 hits)