cstringip-address

Integer to IP Address - C


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!


Solution

  • Here's a simple method to do it: The (ip >> 8), (ip >> 16) and (ip >> 24) moves the 2nd, 3rd and 4th bytes into the lower order byte, while the & 0xFF isolates the least significant byte at each step.

    void print_ip(unsigned int ip)
    {
        unsigned char bytes[4];
        bytes[0] = ip & 0xFF;
        bytes[1] = (ip >> 8) & 0xFF;
        bytes[2] = (ip >> 16) & 0xFF;
        bytes[3] = (ip >> 24) & 0xFF;   
        printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);        
    }
    

    There is an implied bytes[0] = (ip >> 0) & 0xFF; at the first step.

    Use snprintf() to print it to a string.