Necessary_Function
Necessary_Function

Reputation: 43

InetPtonW always returns 1.0.0.0

I just started learning C and now I'm learning how to use the winsock2-Header. To convert an ip address from the string representation to its binary form I use the function InetPtonW. My problem is that this function always returns the IP adress 1.0.0.0.

I'm using Visual Studio on Windows 10. I read the documentation from Microsoft (see here) and I also read this question on Stackoverflow. I tried different things using other data types but I could not get the correct result.

Below is the relevant code for my problem.

int main() {
    WSADATA wsa;
    SOCKET s;
    struct sockaddr_in server;
    PCWSTR pStringIp = (L"172.217.168.14"); //IP for own webserver
    PVOID pAddrBuf;
    char* message;
    char* recvbuf; // Buffer for the reply
    int recvbuflen = DEFAULT_BUFLEN; //Size of the reply from the server
/* Socket creation etc. would be here */
    pAddrBuf = malloc(INET6_ADDRSTRLEN);
    if (pAddrBuf == NULL) {
        printMemoryErrorFailMessage(errno, pAddrBuf);
        return EXIT_FAILURE;
    }
    server.sin_addr.s_addr = InetPtonW(AF_INET, pStringIp, pAddrBuf);
    free(pAddrBuf);
}

I expect that in the example the ip address will be converted to 172.217.168.14 but not 1.0.0.0

If you need more information or more code, just ask. Thanks for your help.

Kindly Necessary_Function

Upvotes: 0

Views: 737

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

From the InetPtonW documentation:

  • For the argument pAddrBuf

    A pointer to a buffer in which to store the numeric binary representation of the IP address. The IP address is returned in network byte order.

  • For the returned value

    If no error occurs, the InetPton function returns a value of 1 and the buffer pointed to by the pAddrBuf parameter contains the binary numeric IP address in network byte order.

To summarize: The function returns a boolean 1 or 0 depending on if it succeeds or fails; And if it succeeds it writes the address into the memory pointed to by pAddrBuffer (the third argument).

The reason you get the address 1.0.0.0 is because you use the returned boolean result as the address, while discarding the actual address that was written to the memory pointed to by pAddrBuf.

The "correct" way to use the function would be something like this:

if (InetPtonW(AF_INET, pStringIp, &server.sin_addr.s_addr) == 1)
{
    // Success, use the address some way
}

Upvotes: 3

Related Questions