planetp
planetp

Reputation: 16065

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

Upvotes: 12

Views: 8129

Answers (5)

janus-py
janus-py

Reputation: 17

I also needed to implement such a check. Reading the documentation of ipaddress module, I found the function overlaps(). It works. Code example:

import ipaddress
from ipaddress import IPv4Network

supernet = IPv4Network('10.0.0.0/8')
net = IPv4Network('11.0.10.0/30')
print(net.overlaps(supernet))

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149726

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.

Upvotes: 12

user9569493
user9569493

Reputation: 1

For some reason, the ipaddress module does not provide a simple function to check whether a network is contained in another network. I managed to solve this problem as follows:

ip1 = '10.0.0.0/24' ip2 = '10.0.0.22' ipaddress.ip_network(ip2) in ipaddress.ip_network(ip1).subnets(new_prefix=ipaddress.ip_network(ip2).prefixlen)

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56624

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

Upvotes: 7

Learner
Learner

Reputation: 5292

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!"

Upvotes: 5

Related Questions