Given two CIDR addresses say 192.168.2.0/14 and 192.168.2.0/32
How do I check if two ip addresses overlap in "python2.6"??
I have gone through netaddr and it allows to check if 192.168.2.0 is in CIDR address 192.168.2.0/14 by
from netaddr import IPNetwork, IPAddress
bool = IPAddress("192.168.2.0") in IPNetwork("192.168.2.0/14"):
But how to check for two CIDR address??
I found a reference :: How can I check if an ip is in a network in python
Using ipaddr:
If don't have
netaddr
at hand for testing, but I think you could check if the first and last address of the first network are both contained in the second:BTW,
IPNetwork
line 1102 defines a__contains__
method. But I'm not certain the line 1127 isn't broken ? You should test and report a bug if it is.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:
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: