Check if two CIDR addresses overlap?

Given two CIDR addresses: 192.168.2.0/14 and 192.168.2.0/32

How to check if two IP addresses overlap in "python2.6" ??

I went through netaddr and this allows me to check if 192.168.2.0 is in the CIDR address of 192.168.2.0/14 on

from netaddr import IPNetwork, IPAddress bool = IPAddress("192.168.2.0") in IPNetwork("192.168.2.0/14"): 

But how to check two CIDR addresses

I found the link :: How to check if ip is online in python

+13
source share
4 answers

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 
+17
source

I assume that you really want both CIDRs to represent ranges, although in your example 192.168.2.0/32 is only one address. Also note that in 192.168.2.0/14,.2. does not make sense, since the 14-bit prefix does not reach the third octet.

In any case, there are several ways to do this. You may have noticed that for overlapping they should always be a subset of the other:

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

Or you may have noticed that for overlapping ranges, the lower address of the first range must be less than or equal to the highest address of the second range and vice versa. Thus:

 def cidrsOverlap(cidr0, cidr1): return cidr0.first <= cidr1.last and cidr1.first <= cidr0.last print cidrsOverlap(IPNetwork('192.168.2.0/24'), IPNetwork('192.168.3.0/24')) # prints False print cidrsOverlap(IPNetwork('192.168.2.0/23'), IPNetwork('192.168.3.0/24')) # prints True 
+5
source

If you do not have netaddr to test, but I think you could check if the last address of the first network is really in the second:

 net_1 = IPNetwork("192.168.2.0/14") net_2 = IPNetwork("192.168.2.0/32") if net_1.first in net_2 and net_1.last in net_2: # do something 

BTW, IPNetwork line 1102 defines the __contains__ method. But I'm not sure if line 1127 is broken? You should check and report an error, if any.

+1
source

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

 pip install ipconflict 

Example:

 ipconflict 10.0.0.0/22 10.0.1.0/24 

Exit:

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

All Articles