AlexW AlexW - 1 month ago 10
Python Question

IPaddress - find the next usable /30 network from a list of /30s?

I have a list of ipaddress networks as such:

172.16.1.0/30
172.16.1.4/30
172.16.1.8/30
172.16.1.12/30
172.16.1.20/30
172.16.1.24/30


They are created as per below:

sr_data = SiteConfigData.objects()

ls_subnets = []
for r in sr_data:
if r.ip != '0.0.0.0':
ls_subnets.append(ipaddress.ip_network(r.ip + '/30'))


I'm not sure how to do this, but I would like a function to return the next available
/30
, so the first result should be
172.16.1.16/30
then once that is used the next result should be
172.16.1.28/30
.

The list of subnets may also not be in order...

Is this possible? I can't seem to wrap my head around what logic I would need to make this work.

Answer

ip_addresses list is just like ls_subnets of your code.

ip_addresses = [
    "172.16.1.0/30",
    "172.16.1.4/30",
    "172.16.1.8/30",
    "172.16.1.12/30",
    "172.16.1.20/30",
    "172.16.1.24/30",
    ] # Assuming the input is neat
used_subnets = []
for ip_address in ip_addresses:
    ip_address = ip_address.replace("/30","")
    a,b,c,d = map(int,ip_address.split('.'))
    used_subnets.append(d)
unused_subnets = ['172.16.1.%d/30'%num for num in range(0,30,4) if num not in used_subnets]