Search code examples
cip-address

IP address to binary in C


I have an ip address like so:

address = '192.168.1.11';

and need to convert it to its binary format

11000000 10101000 00000001 00001011

I have some ideas on how to leftshift the decimal number and using inet_addr, but not sure how I would go about doing it.

Thanks, I'm still new to C.


Solution

  • There is a socket function specific for transforming text IP into a 32-bit "longip" address, but this might be unecessary in this context. A simple form would be to parse it using sscanf():

    char ip[] = "192.168.1.11";
    int n1, n2, n3, n4;
    sscanf(ip, "%d.%d.%d.%d", &n1, &n2, &n3, &n4).
    
    // Result:
    
    // n1 = 192
    // n2 = 168
    // n3 = 1
    // n4 = 11