【发布时间】:2014-09-14 14:08:51
【问题描述】:
我正在尝试通过ICMP 向某个 IP 发送 ping,但 InetPton() 函数(假设将字符串 IP 转换为二进制形式)总是返回相同的 ip:"1.0.0.0 ".
我的代码如下所示:
short ip[4] = { 192, 168, 1, 2 };
bool checkIP() {
HANDLE hIcmpFile;
unsigned long ipaddr = INADDR_NONE;
DWORD dwRetVal = 0;
char SendData[32] = "Data Buffer";
LPVOID ReplyBuffer = NULL;
DWORD ReplySize = 0;
std::wostringstream strIP;
strIP << ip[0] << "." << ip[1] << "." << ip[2] << "." << ip[3];
in_addr ipAddress;
ipaddr = InetPton(AF_INET, strIP.str().c_str(), &ipAddress);
if (ipaddr != 1)
{
SendMessage((HWND)StatusBar, (UINT)SB_SETTEXT, (WPARAM)(INT)1 | 0, (LPARAM)(LPSTR)TEXT("Invalid IP format!"));
return false;
}
hIcmpFile = IcmpCreateFile();
if (hIcmpFile == INVALID_HANDLE_VALUE)
{
SendMessage((HWND)StatusBar, (UINT)SB_SETTEXT, (WPARAM)(INT)1 | 0, (LPARAM)(LPSTR)TEXT("Unable to open ICMP handle!"));
return false;
}
ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
ReplyBuffer = (VOID*)malloc(ReplySize);
if (ReplyBuffer == NULL)
{
SendMessage((HWND)StatusBar, (UINT)SB_SETTEXT, (WPARAM)(INT)1 | 0, (LPARAM)(LPSTR)TEXT("Unable to allocate memory!"));
return false;
}
dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, 2000);
if (dwRetVal != 0)
{
PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;
struct in_addr ReplyAddr;
ReplyAddr.S_un.S_addr = pEchoReply->Address;
IcmpCloseHandle(hIcmpFile);
return true;
}
else {
IcmpCloseHandle(hIcmpFile);
return false;
}
return true;
}
所以,我正在使用WireShark 分析网络,我可以看到 PING 总是发送到 1.0.0.0。我想问题出在InetPton()函数上,但不明白在哪里。
【问题讨论】:
标签: c++ ip-address ping data-conversion icmp