Skip to content

Instantly share code, notes, and snippets.

@spdkils
Created January 17, 2019 16:19
Show Gist options
  • Save spdkils/3f51393b1bf69b83c9b0a13a3d9f9af3 to your computer and use it in GitHub Desktop.
Save spdkils/3f51393b1bf69b83c9b0a13a3d9f9af3 to your computer and use it in GitHub Desktop.
subnet squeeze
from typing import List
import ipaddress
lst = ['10.10.20.0/24',
'10.10.30.0/25',
'10.10.30.128/25',
'10.10.31.0/24',
'10.10.32.0/24'
]
filtered_lst = list(filter(lambda x: '/3' not in x, lst))
network_list = [ipaddress.IPv4Network(x) for x in filtered_lst]
network_list.sort()
def adjacent_network(net1: ipaddress.IPv4Network, net2: ipaddress.IPv4Network):
if net2 <= net1:
net1, net2 = net2, net1
if (net1.broadcast_address == net2.network_address - 1
and net1.prefixlen == net2.prefixlen
and int(net1.network_address) == int(net1.network_address) & int(net2.broadcast_address)):
return True
def compress_contiguous(net_lst: List[ipaddress.IPv4Network]):
work = True
while work:
work = False
for idx in range(len(net_lst)-1):
if adjacent_network(net_lst[idx], net_lst[idx+1]):
work = True
net_lst[idx] = ipaddress.IPv4Network(f'{net_lst[idx].network_address.compressed}/{net_lst[idx].prefixlen-1}')
del net_lst[idx+1]
break
return net_lst
print()
print(network_list)
print()
compress_contiguous(network_list)
print(network_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment