c++cnetwork-programmingip

IP Address overlapping/in range of CIDR


I have an IP address in unsigned long format, coding in C++ I have a CIDR notation IP address range such as "10.2.3.98/24"

How do i check if my IP address overlaps with the mentioned range?


Solution

  • This should work if you already know ip addresses as unsigned long and numbers:

    bool cidr_overlap(uint32_t ip1, int n1,
                      uint32_t ip2, int n2)
    {
        return (ip1 <= (ip2 | ((1ul << (32-n2))-1)))
            && (ip2 <= (ip1 | ((1ul << (32-n1))-1)));
    }