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

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

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.


Try netaddr as below-

Check if a network is in another

from netaddr import IPNetwork,IPAddress

if IPNetwork("10.11.12.0/24") in IPNetwork("10.11.0.0/16"):
    print "Yes it is!"

Check if an IP is in a network

from netaddr import IPNetwork,IPAddress

if IPAddress("10.11.12.0") in IPNetwork("10.11.0.0/16"):
    print "Yes it is!"