Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a network is contained in another network in Python?

How can I check if a network is wholly contained in another network in Python, e.g. if 10.11.12.0/24 is in 10.11.0.0/16?

I've tried using ipaddress but it doesn't work:

>>> import ipaddress
>>> ipaddress.ip_network('10.11.12.0/24') in ipaddress.ip_network('10.11.0.0/16')
False
like image 938
planetp Avatar asked Jan 31 '16 14:01

planetp


2 Answers

Starting from Python 3.7.0 you can use the subnet_of() and supernet_of() methods of ipaddress.IPv6Network and ipaddress.IPv4Network for network containment tests:

>>> from ipaddress import ip_network
>>> a = ip_network('192.168.1.0/24')
>>> b = ip_network('192.168.1.128/30')
>>> b.subnet_of(a)
True
>>> a.supernet_of(b)
True

If you have a Python version prior to 3.7.0, you can just copy the method's code from the later version of the module.

like image 85
Eugene Yarmash Avatar answered Sep 19 '22 02:09

Eugene Yarmash


import ipaddress

def is_subnet_of(a, b):
   """
   Returns boolean: is `a` a subnet of `b`?
   """
   a = ipaddress.ip_network(a)
   b = ipaddress.ip_network(b)
   a_len = a.prefixlen
   b_len = b.prefixlen
   return a_len >= b_len and a.supernet(a_len - b_len) == b

then

is_subnet_of("10.11.12.0/24", "10.11.0.0/16")   # => True
like image 26
Hugh Bothwell Avatar answered Sep 21 '22 02:09

Hugh Bothwell