首页 > 代码库 > Windows下Ping功能的实现(VC++)
Windows下Ping功能的实现(VC++)
网上的实现Ping功能的代码很多,以前用过一段代码,在windows user组用户下操作会失败,下面贴出一个可用的
// 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"));
}
Windows下Ping功能的实现(VC++)