Skip to content Skip to sidebar Skip to footer

The Algorithm For Dividing The Range Of Subnet

There is a interesting algorithm, wrt dividing the range of subnet. I have a subnet,such as 192.168.1.0/24 or 192.168.1.248/22, and so on. And we know that '/24' or '/22' stands fo

Solution 1:

Do you want an algorithm, or do you want a solution?

For a solution, in Python 3, use the ipaddress module. There is a backport to Python 2 available in PyPI.

If you want the algorithm, you can read the code for the module.

Using the ipaddress module:

import ipaddress
network = ipaddress.ip_network('192.168.1.0/24')
hosts = list(network.hosts())
subnets = [{'start_address': str(list(subnet.hosts())[0]),
            'end_address': str(list(subnet.hosts())[-1])}
                   for subnet in network.subnets()]
print(subnets)

Output

[{'start_address': '192.168.1.1', 'end_address': '192.168.1.126'}, {'start_address': '192.168.1.129', 'end_address': '192.168.1.254'}]

Which is pretty close to what you want. Missing is 192.168.1.127 which is the broadcast address for the first subnet, 192.168.1.128 which is the network address for the second subnet, and 192.168.1.255 which is the broadcast address for the second subnet.

To achieve the exact output you can split the hosts list:

hosts = list(network.hosts())
subnets = [{'start_address': str(subnet[0]), 'end_address': str(subnet[-1])} 
               for subnet in (hosts[:len(hosts)//2], hosts[len(hosts)//2:])]
print(subnets)

Output

[{'start_address': '192.168.1.1', 'end_address': '192.168.1.127'}, {'start_address': '192.168.1.128', 'end_address': '192.168.1.254'}]

Post a Comment for "The Algorithm For Dividing The Range Of Subnet"