2017-07-25 233 views
-1

//編輯:有沒有錯的代碼,我只是完全愚蠢地忘記它提供@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; 
} 

是代碼失去了一些東西的代碼?或者我只是沒有正確使用它,任何幫助將不勝感激。

+0

這不是一個崩潰。這是代碼告訴你,你應該在命令行中包含一個IP地址,告訴它在哪裏發送ICMP迴應數據包。 –

+0

非常感謝您的回覆,我在當天晚些時候發現了這個問題,我想我只是如此地洞察力,以至於我並不只是看看主要的參數。只是不得不在運行時給它提供參數。再次感謝很多! –

回答

0

要小心!上面的MSDN代碼確實是不是免費的 ReplyBuffer。 我建議在每次退貨之前取消分配:

.. 

     free(ReplyBuffer); 
     return 4; 
.. 
     free(ReplyBuffer); 
     return 0;