i am having a list of subnets and i need to find all the biggest subnets from a list of subnets that are supernets among subnets present in the list.
example
subnetList = ['10.10.0.0/16', '10.10.10.10/32', '192.168.56.0/24', '10.0.0.0/8']
so output here ['10.0.0.0/8', '192.168.56.0/24']
are the two top level supernet among different subnet present in the list
to solve this i am currently using using implementation using ipaddress python lib,
is there any better implementation !!!! since this problem seems to be like finding multiple max of different types present in a list
import ipaddress
inputS = ['172.16.0.0/16' ,'10.10.0.0/16', '10.10.10.10/32', '172.16.1.0/24', '10.10.10.0/24', '172.16.10.10/32', '192.168.56.0/24', '10.0.0.0/8']
inputS = list(set(inputS))
input = []
for each in inputS:
input.append(ipaddress.ip_network(str(each)))
input1 = input
for i in range(len(input)):
for j in range(len(input1)):
if str(input[i]) != str(input1[j]):
if input[i].supernet_of(input1[j]):
input1[j] = input[i]
output = []
for each in input1:
output.append(str(each))
print(list(set(output)))
ipaddress library in python has a function collapse_addresses. collapse_addresses function should be able to give you a direct output of supernets from the list of input ipaddresses.
Please check the below code snippet:
>>> import ipaddress
>>> inputS = ['172.16.0.0/16' ,'10.10.0.0/16', '10.10.10.10/32', '172.16.1.0/24', '10.10.10.0/24', '172.16.10.10/32', '192.168.56.0/24', '10.0.0.0/8']
>>> input_ips = [ipaddress.ip_network(x) for x in inputS]
>>> res = ipaddress.collapse_addresses(input_ips)
>>> print([x for x in res])
[IPv4Network('10.0.0.0/8'), IPv4Network('172.16.0.0/16'), IPv4Network('192.168.56.0/24')]