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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With