Search code examples
c++cipip-addresslan

Is there a library function to determine if an IP address (IPv4 and IPv6) is private/local in C/C++?


1, Given a 32-bit integer value, how to exactly determine if it is private IPv4 address.

2, Given a 128-bit integer value, how to exactly determine if it is private IPv6 address.

Consider the byte order of the IP address on different platforms, it is error-prone to write such a common little function every time. So I think there should be a library function for this, is there?


Solution

  • This will get you started. I didn't bother including the "link local" address range, but that's an exercise left for you to complete by modifying the code below.

    IPV6 is slightly different. And your question is slightly malformed since most systems don't have a native 128-bit type. IPv6 addresses are usually contained as an array of 16 bytes embedded in a sockaddr_in6 struct.

    Everything you need to know to finish this example is at this link here.

    // assumes ip is in HOST order.  Use ntohl() to convert as approrpriate
    
    bool IsPrivateAddress(uint32_t ip)
    {
        uint8_t b1, b2, b3, b4;
        b1 = (uint8_t)(ip >> 24);
        b2 = (uint8_t)((ip >> 16) & 0x0ff);
        b3 = (uint8_t)((ip >> 8) & 0x0ff);
        b4 = (uint8_t)(ip & 0x0ff);
    
        // 10.x.y.z
        if (b1 == 10)
            return true;
    
        // 172.16.0.0 - 172.31.255.255
        if ((b1 == 172) && (b2 >= 16) && (b2 <= 31))
            return true;
    
        // 192.168.0.0 - 192.168.255.255
        if ((b1 == 192) && (b2 == 168))
            return true;
    
        return false;
    }