问题
I am trying to send a ping to some IP through ICMP but the InetPton()
function, which is suppose to convert string IPs into a binary form, is always returning the same ip: "1.0.0.0".
My code looks like this:
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;
}
So, I am analyzing the network with WireShark and I can see that the PING is always sent to 1.0.0.0. I suppose that the problem lies in the InetPton()
function, but don't understand where.
回答1:
IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, 2000);
Should be:
IcmpSendEcho(hIcmpFile, ipAddress, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, 2000);
Your ipaddr
is 1, probably this is the source of 1.0.0.0
address.
回答2:
Your code seems a bit off here;
in_addr* ipAddress;
ipaddr = InetPton(AF_INET, strIP.str().c_str(), &ipAddress);
ipAddress
will here be an un-initialized pointer to an in_addr
, which you pass a pointer to into InetPton. What InetPton really wants is a pointer to an actual struct/buffer it can fill;
in_addr ipAddress;
ipaddr = InetPton(AF_INET, strIP.str().c_str(), &ipAddress);
来源:https://stackoverflow.com/questions/25834117/inetpton-converts-any-ip-to-1-0-0-0