Subnetting in Python

Another use case is an IP subnetting application, which gives you the required IP subnets based on required network size or amount of networks per location. We can also find the subnet information from the IPv4Network objects, as follows:

>>> net4.subnets()
<generator object _BaseNetwork.subnets at 0x02F2C0C0>
>>> subnets = list( net4.subnets())
>>> subnets
[ IPv4Network('10.0.1.0/25'), IPv4Network('10.0.1.128/25') ]

The ipaddress module includes many functions to create subnets and supernets; for example, we can use these methods to check whether a network overlaps with another:

>>> ipnet = ipaddress.IPv4Network("10.2.0.0/16")
>>> list(ipnet.subnets())
[IPv4Network('10.2.0.0/17'), IPv4Network('10.2.128.0/17')]

The subnets(prefixlen_diff=1, new_prefix=None) method also has the capacity to generate subnets with additional host bits or with a specific amount of network bits. In the following example, we use the new_prefix argument in the subnets method to define the number of network bits for the new network mask:

# new_prefix = number of network bits for the new mask
>>> list(ipnet.subnets(new_prefix=20))
[IPv4Network('10.2.0.0/20'), IPv4Network('10.2.16.0/20'), IPv4Network('10.2.32.0/20'), IPv4Network('10.2.48.0/20'), IPv4Network('10.2.64.0/20'), IPv4Network('10.2.80.0/20'), IPv4Network('10.2.96.0/20'), IPv4Network('10.2.112.0/20'), IPv4Network('10.2.128.0/20'), IPv4Network('10.2.144.0/20'), IPv4Network('10.2.160.0/20'), IPv4Network('10.2.176.0/20'), IPv4Network('10.2.192.0/20'), IPv4Network('10.2.208.0/20'), IPv4Network('10.2.224.0/20'), IPv4Network('10.2.240.0/20')]

Any IPv4Network object can tell, which is the opposite of the subnet by looking at its parent supernet:

>>> net4.supernet()
IPv4Network('10.0.0.0/23')
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset