FastSolutions
FastSolutions

Reputation: 1829

[C]Convert Decimal IP To Dotted Decimal Notation

I got the following Decimal IP: "3232235876" it represents "192.168.1.100"

I got it in the following way:

   //GET IP
        if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
            printf("%s","host not found");
        }

        struct hostent *phe = gethostbyname(hostname);
        memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr));

        //Convert IP to Decimal notation
        sprintf(decResult,"%u", addr);
        sprintf(decResult,"%u", htonl(atoi(decResult))); 

But now is my question how do I reconvert it to the Dotted Decimal Notation?

I know it's done with 'inet_ntoa' function but I first need to get '3232235876' converted something else and then I need to convert that to addr.

To both those questions I don't know the answer :/

Kind regards.

Upvotes: 1

Views: 2178

Answers (1)

DarkDust
DarkDust

Reputation: 92384

Use inet_ntoa to convert the address into a string:

if (gethostname(hostname, sizeof(hostname)) == -1) {
    printf("host not found");
    return;
}

struct hostent *phe = gethostbyname(hostname);
if (phe == NULL) {
    printf("Could resolve %s!", hostname);
    return;
}

struct in_addr **addr_list = (struct in_addr **)phe->h_addr_list;
char *addr_str = inet_ntoa(*addr_list[0]);

You can also iterate the list of addresses like this:

for (int i = 0; addr_list[i] != NULL; i++) {
    printf("%s ", inet_ntoa(*addr_list[i]));
}

See the example code in this gethostbyname man page. Note that gethostbyname is deprecated as it doesn't work with IPv6. You should use getaddrinfo instead. Again, see the man page for example code.

Upvotes: 4

Related Questions