Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two CIDR addresses intersect?

Tags:

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

like image 359
AjanShrestha Avatar asked Jun 20 '13 06:06

AjanShrestha


People also ask

Do CIDRs overlap?

Network Address Translation (NAT) is a common technique to connect two networks with overlapping CIDRs. Often times, the connectivity between these two networks need to be encrypted with IPSec.

Do IP ranges overlap?

An overlapping IP address occurs when an IP address is assigned to more than one device on a network. This can happen if you have identical subnets in different locations monitored by different DHCP servers on the same network.

Do subnets overlap?

Regardless of whether a design uses VLSM, the subnets used in any IP internetwork design should not overlap their address ranges. When subnets in different locations overlap their addresses, a router's routing table entries overlap. As a result, hosts in different locations can be assigned the same IP address.

What are overlapping IPS?

An overlapping IP address is an IP address that is assigned to more than one device or logical unit, such as an event source type, on a network.


2 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 
like image 53
falsetru Avatar answered Oct 14 '22 23:10

falsetru


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.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 
like image 45
rob mayoff Avatar answered Oct 14 '22 23:10

rob mayoff