InetPton() converts any IP to 1.0.0.0

我是研究僧i 提交于 2020-01-25 01:59:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!