The online implementation of the ping function of a lot of code, previously used a piece of code, the Windows user group under the user operation will fail, the following post a usable
PING.cpp:Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>
#include <stdlib.h>
#include <stdio.h>
#pragma comment (lib, "Iphlpapi.lib")
#pragma comment (lib, "Ws2_32.lib")
int myping (const char *szip)
{
Declare and Initialize variables
HANDLE Hicmpfile;
unsigned long ipaddr = Inaddr_none;
DWORD dwretval = 0;
DWORD dwerror = 0;
Char senddata[] = "Data Buffer";
LPVOID replybuffer = NULL;
DWORD replysize = 0;
Validate the parameters
ipaddr = inet_addr (Szip);
Hicmpfile = Icmpcreatefile ();
if (Hicmpfile = = Invalid_handle_value) {
printf ("\tunable to open handle.\n");
printf ("Icmpcreatefile returned error:%ld\n", GetLastError ());
return 1;
}
Allocate space for at a single reply
replysize = sizeof (icmp_echo_reply) + sizeof (SendData) + 8;
Replybuffer = (VOID *) malloc (replysize);
if (Replybuffer = = NULL) {
printf ("\tunable to allocate memory for reply buffer\n");
return 1;
}
Dwretval = IcmpSendEcho2 (hicmpfile, NULL, NULL, NULL,
IPAddr, SendData, sizeof (SendData), NULL,
Replybuffer, replysize, 1000);
if (dwretval! = 0) {
Picmp_echo_reply pechoreply = (picmp_echo_reply) replybuffer;
struct IN_ADDR replyaddr;
Replyaddr.s_un. S_ADDR = pechoreply->address;
printf ("\tsent ICMP message to%s\n", szip);
if (Dwretval > 1) {
printf ("\treceived%ld ICMP message responses\n", dwretval);
printf ("\tinformation from the first response:\n");
} else {
printf ("\treceived%ld ICMP message response\n", dwretval);
printf ("\tinformation from this response:\n");
}
printf ("\ t Received from%s\n", Inet_ntoa (REPLYADDR));
printf ("\ t Status =%ld", pechoreply->status);
Switch (pechoreply->status) {
Case Ip_dest_host_unreachable:
printf ("(Destination host was unreachable) \ n");
Break
Case Ip_dest_net_unreachable:
printf ("(Destination Network was unreachable) \ n");
Break
Case Ip_req_timed_out:
printf ("(Request timed out) \ n");
Break
Default
printf ("\ n");
Break
}
printf ("\ t roundtrip time =%ld milliseconds\n",
Pechoreply->roundtriptime);
Free (replybuffer);
} else {
printf ("Call to IcmpSendEcho2 failed.\n");
dwerror = GetLastError ();
Switch (dwerror) {
Case Ip_buf_too_small:
printf ("\treplybuffersize to small\n");
Break
Case Ip_req_timed_out:
printf ("\trequest timed out\n");
Break
Default
printf ("\textended error returned:%ld\n", dwerror);
Break
}
return 1;
}
return 0;
}
int main (int argc, char* argv[])
{
printf ("\n%d\n", Myping ("192.168.0.103"));
}
Implementation of the Ping function under Windows (VC + +)