- system在能ping通或无法访问目标主机的情况返回0,ping包丢失(请求超时)则返回1:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char * argv[]) {
string a = "192.168.70.2";
char buffer[128];
sprintf_s(buffer,"ping %s -n 1",a.c_str());
int res=system(buffer);
cout << "返回:" << res << endl;
res=system("ping 163.com -n 1");
cout << "返回:" << res << endl;
system("pause");
return 0;
}
- 用微软接口函数IcmpSendEcho2发送icmp包
int ping(string IP){
// 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
char * ip = (char*)IP.c_str();
//ipaddr = inet_addr(ip);
inet_pton(AF_INET, ip, &ipaddr);
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", ip);
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);
}
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;
}
网友评论