Skip to content

Instantly share code, notes, and snippets.

@jmacego jmacego/
Last active Mar 19, 2019

What would you like to do?
Efficiently create a number of subnets out of a larger prefix
from __future__ import print_function
import ipaddress
def do_vlsm(sorted_vlans):
supernet = input("Supernet: ") or ""
current_subnet = ipaddress.ip_network(supernet)
available_subnets = [current_subnet]
print("\nSubnet Lengths:")
for vlan in sorted_vlans:
if vlan['subnet_len'] == 0:
print("VLAN: {} will not be used.".format(vlan['name']))
tentative_subnet = ''
for x in range(0, 32):
if tentative_subnet:
for subnet in available_subnets:
if subnet.prefixlen == vlan['subnet_len'] - x:
tentative_subnet = list(subnet.subnets(new_prefix=vlan['subnet_len']))[0]
available_subnets = (available_subnets
+ list(subnet.address_exclude(tentative_subnet)))
remaining_subnets = []
for a in available_subnets[:]:
if not a.overlaps(tentative_subnet):
available_subnets = remaining_subnets
vlan['subnet'] = str(tentative_subnet)
print("Used Prefixes:")
for vlan in sorted_vlans:
print("{},{},{}".format(vlan['name'], vlan['vlan_id'], vlan['subnet']))
print("Remaining Prefixes:")
for subnet in sorted(available_subnets):
return sorted_vlans, available_subnets, supernet
def get_vlan_input():
vlans = []
print("Leave VLAN blank when finished")
vlan_name = input("VLAN Name: ")
if not vlan_name:
vlan_id = input("VLAN ID: ")
if not 1 <= int(vlan_id) <= 4094:
vlan_id = input("VLAN ID must be 1-4094: ")
subnet_len = input("Subnet length: /")
if not 0 <= int(subnet_len) <= 32:
subnet_len = input("Subnet Len must be 0-32: /")
vlans.append({'name': vlan_name, 'subnet_len': int(subnet_len), 'vlan_id': vlan_id})
return sorted(vlans, key=lambda k: k['subnet_len'])

This comment has been minimized.

Copy link
Owner Author

jmacego commented Mar 11, 2019

pip install ipaddress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.