AlexW AlexW - 3 months ago 23
Python Question

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

I have a list of ipaddress networks as such:

They are created as per below:

sr_data = SiteConfigData.objects()

ls_subnets = []
for r in sr_data:
if r.ip != '':
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
, so the first result should be
then once that is used the next result should be

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.


ip_addresses list is just like ls_subnets of your code.

ip_addresses = [
    ] # 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('.'))
unused_subnets = ['172.16.1.%d/30'%num for num in range(0,30,4) if num not in used_subnets]