Skip to content

Instantly share code, notes, and snippets.

@jnhmcknight
Last active July 26, 2023 16:20
Show Gist options
  • Save jnhmcknight/236d0e8b422996c00da035c1fcc83476 to your computer and use it in GitHub Desktop.
Save jnhmcknight/236d0e8b422996c00da035c1fcc83476 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""Show subnets information.
Given an IP network in CIDR notation and the minimum number of desired subnets,
this script will provide the relevant information about the desired subnets.
Example:
$ ./subnet-divider.py 10.10.0.34/16 4
$ ./subnet-divider.py fd3e:48fe:59b2:43ca::/64 15
Adapted from:
https://github.com/eyablokov/subnet-divider
"""
import math
import sys
import ipaddress
def divide_network(network, parts):
""" Generator to return the resulting subnets after dividing a main network """
if parts <= 1:
subnet_diff = 0
elif (parts & (parts - 1)) == 0:
subnet_diff = int(math.log2(parts))
else:
subnet_diff = int(math.log2(parts)) + 1
if (subnet_diff+network.prefixlen) > network.max_prefixlen:
print('Unable to divide the given network into that many subnets')
sys.exit(1)
for subnet in network.subnets(prefixlen_diff=subnet_diff):
yield subnet
# Get the main network, to divide onto predefined parts
net = ipaddress.ip_network(sys.argv[1], strict=False)
# Get the require number of subnets to which the network will be divided
parts = int(sys.argv[2])
for subnet in divide_network(net, parts):
print("")
print(f"CIDR: {subnet}")
print(f"Netmask: {subnet.netmask}")
print(f"Network: {subnet.network_address}")
if subnet.num_addresses == 1:
print(f"Host Count: 1")
else:
print(f"Gateway: {subnet.network_address+1}")
print(f"Broadcast: {subnet.broadcast_address}")
print(f"Host Count: {subnet.num_addresses-1}")
@jnhmcknight
Copy link
Author

This is deprecated, since it was migrated to the published subnet-utils package: https://github.com/fictivekin/subnet-utils/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment