Writing a ping program

The windows "ping" command sends an ICMP Echo Request packet, and see if the destination host is alive. IPHLPAPI provides an API to send and receive ICMP Echo to check if the destination host is up. The IcmpSendEcho() API sends and receives ICMP Echo. In this page, usage of IcmpSendEcho() is shown.

Sample code

The following sample code shows how to use IcmpSendEcho().

Please note that IcmpSendEcho() is different from the other IPHLPAPI APIs. First of all, to use IcmpSendEcho(), you must include "icmpapi.h" header. Next, you must add "icmp.lib" to the linking library list.

The location where "icmpapi.h" and "icmp.lib" are installed depends on systems. In my system, "icmpapi.h" was installed in "(Platform SDK folder)\Misc\Icmp\icmpapi.h". "icmp.lib" was installed in "(Platform SDK folder)\Misc\Icmp\Lib\icmp.lib".


#include <stdio.h>

#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>

int
main()
{
 HANDLE hIcmp;
 char *SendData = "ICMP SEND DATA";
 LPVOID ReplyBuffer;
 DWORD dwRetVal;
 DWORD buflen;
 PICMP_ECHO_REPLY pIcmpEchoReply;

 hIcmp = IcmpCreateFile();

 buflen = sizeof(ICMP_ECHO_REPLY) + strlen(SendData) + 1;
 ReplyBuffer = (VOID*) malloc(buflen);
 if (ReplyBuffer == NULL) {
   return 1;
 }
 memset(ReplyBuffer, 0, buflen);
 pIcmpEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;

 dwRetVal = IcmpSendEcho(hIcmp, 
   inet_addr("127.0.0.1"), 
   SendData, strlen(SendData), 
   NULL, ReplyBuffer, 
   buflen,
   1000);
 if (dwRetVal != 0) {
   printf("Received %ld messages.\n", dwRetVal);
   printf("\n");
   printf("RTT: %d\n", pIcmpEchoReply->RoundTripTime);
   printf("Data Size: %d\n", pIcmpEchoReply->DataSize);
   printf("Message: %s\n", pIcmpEchoReply->Data);
 } else {
   printf("Call to IcmpSendEcho() failed.\n");
   printf("Error: %ld\n", GetLastError());
 }

 IcmpCloseHandle(hIcmp);

 return 0;
}

Sample code output

The sample will output an message like the following.


C:> a.exe
Received 1 messages.

RTT: 0
Data Size: 14
Message: ICMP SEND DATA

ICMP_ECHO_REPLY Structure

The following structure is ICMP_ECHO_REPLY that is used by IcmpSendEcho().


typedef struct icmp_echo_reply {
  IPAddr Address;
  ULONG Status;
  ULONG RoundTripTime;
  USHORT DataSize;
  USHORT Reserved;
  PVOID Data;
  IP_OPTION_INFORMATION Options;
} ICMP_ECHO_REPLY, *PICMP_ECHO_REPLY;

Address IP address.
Status Echo Request status. Please see IP_STATUS in IPExport.h for more detail.
RoundTripTime RTT. msec.
DataSize Size of reply data. (byte)
Reserved Unused.
Data Pointer to the ICMP payload (data part).
Options ICMP Reply options. IP_OPTION_INFORMATION.

Note

Please note that IcmpSendEcho() can only be used with IPv4. When using ICMP with IPv6, please use Icmp6CreateFile() and Icmp6SendEcho2().

  

Copyright (C) GeekPage.JP. All rights reserved.