Integer to IP Address - C

Kris Richards picture Kris Richards · Nov 5, 2009 · Viewed 116.6k times · Source

I'm preparing for a quiz, and I have a strong suspicion I may be tasked with implementing such a function. Basically, given an IP address in network notation, how can we get that from a 32 bit integer into a string in it's dotted decimal notation (something like 155.247.182.83)...? Obviously we can't be using any type of inet functions either...I'm stumped!

Answer

Rose Perrone picture Rose Perrone · Oct 7, 2013

You actually can use an inet function. Observe.

main.c:

#include <arpa/inet.h>

main() {
    uint32_t ip = 2110443574;
    struct in_addr ip_addr;
    ip_addr.s_addr = ip;
    printf("The IP address is %s\n", inet_ntoa(ip_addr));
}

The results of gcc main.c -ansi; ./a.out is

The IP address is 54.208.202.125

Note that a commenter said this does not work on Windows.