pythonip-addresscidr

Check if two CIDR addresses intersect?


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


Solution

  • 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