Check if two CIDR addresses intersect? Check if two CIDR addresses intersect? python python

Check if two CIDR addresses intersect?


Using ipaddr:

>>> import ipaddr>>> n1 = ipaddr.IPNetwork('192.168.1.0/24')>>> n2 = ipaddr.IPNetwork('192.168.2.0/24')>>> n3 = ipaddr.IPNetwork('192.168.2.0/25')>>> n1.overlaps(n2)False>>> n1.overlaps(n3)False>>> n2.overlaps(n3)True>>> n2.overlaps(n1)False


I'll assume you actually want both CIDRs to represent ranges, even though in your example, 192.168.2.0/32 represents only one address. Also note that in 192.168.2.0/14, the .2. is meaningless, because the 14-bit prefix doesn't reach the third octet.

Anyway, there are a several ways to do this. You could notice that for them to overlap, one must always be a subset of the other:

def cidrsOverlap(cidr0, cidr1):    return cidr0 in cidr1 or cidr1 in cidr0

Or you could notice that for the ranges to overlap, the first range's lowest address must be less than or equal to the second range's highest address, and vice versa. Thus:

def cidrsOverlap(cidr0, cidr1):    return cidr0.first <= cidr1.last and cidr1.first <= cidr0.lastprint cidrsOverlap(IPNetwork('192.168.2.0/24'), IPNetwork('192.168.3.0/24'))# prints Falseprint cidrsOverlap(IPNetwork('192.168.2.0/23'), IPNetwork('192.168.3.0/24'))# prints True


I wrote this simple command line tool, based on the netaddr lib.

pip install ipconflict

Example:

ipconflict 10.0.0.0/22 10.0.1.0/24

Output:

conflict found: 10.0.1.0/24 <-> 10.0.1.0/22