IcmpSendEcho微软的示例代码
问题描述:
//编辑:有没有错的代码,我只是完全愚蠢地忘记它提供@run时间参数...IcmpSendEcho微软的示例代码
,所以我尝试使用示例代码微软图书馆网页,https://msdn.microsoft.com/en-us/library/windows/desktop/aa366050(v=vs.85).aspx
enter code here
#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>
#include <stdio.h>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
int __cdecl main(int argc, char **argv) {
// Declare and initialize variables
HANDLE hIcmpFile;
unsigned long ipaddr = INADDR_NONE;
DWORD dwRetVal = 0;
char SendData[32] = "Data Buffer";
LPVOID ReplyBuffer = NULL;
DWORD ReplySize = 0;
// Validate the parameters
if (argc != 2) {
printf("usage: %s IP address\n", argv[0]);
return 1;
}
ipaddr = inet_addr(argv[1]);
if (ipaddr == INADDR_NONE) {
printf("usage: %s IP address\n", argv[0]);
return 1;
}
hIcmpFile = IcmpCreateFile();
if (hIcmpFile == INVALID_HANDLE_VALUE) {
printf("\tUnable to open handle.\n");
printf("IcmpCreatefile returned error: %ld\n", GetLastError());
return 1;
}
ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
ReplyBuffer = (VOID*) malloc(ReplySize);
if (ReplyBuffer == NULL) {
printf("\tUnable to allocate memory\n");
return 1;
}
dwRetVal = IcmpSendEcho(hIcmpFile, 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", argv[1]);
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\n",
pEchoReply->Status);
printf("\t Roundtrip time = %ld milliseconds\n",
pEchoReply->RoundTripTime);
}
else {
printf("\tCall to IcmpSendEcho failed.\n");
printf("\tIcmpSendEcho returned error: %ld\n", GetLastError());
return 1;
}
return 0;
}
我使用Visual Studio 2017年开发CMD使用下面的命令来编译这段代码:CL/EHSC FileName.cpp 代码编译就好了,我去和可执行+的OBJ文件,事情是EXE文件崩溃的时刻,我启动它,以防万一我运行CMD我得到以下我ssage:使用文件名的IP地址基本上是运行这一部分退出,然后因为某些原因
if (argc != 2) {
printf("usage: %s IP address\n", argv[0]);
return 1;
}
是代码失去了一些东西的代码?或者我只是没有正确使用它,任何帮助将不胜感激。
答
要小心!上面的MSDN代码确实是不是免费的 ReplyBuffer。 我建议在每次退货之前取消分配:
..
free(ReplyBuffer);
return 4;
..
free(ReplyBuffer);
return 0;
这不是一个崩溃。这是代码告诉你,你应该在命令行中包含一个IP地址,告诉它在哪里发送ICMP回应数据包。 –
非常感谢您的回复,我在当天晚些时候发现了这个问题,我想我只是如此地洞察力,以至于我并不只是看看主要的参数。只是不得不在运行时给它提供参数。再次感谢很多! –