Home Ask Login Register

Developers Planet

Your answer is one click away!

MoMoney February 2016

Python Lowest Common CIDR

Say I have two IPs: startip = '' and endip = ''

I understand that in python netaddr.iprange_to_cidrs(startip, endip) will give you a list of CIDR subnets that fit exactly between the boundaries. However, I was hoping to go for one CIDR subnet that covers it all even if it gives a few more IPs.

I prefer a function that does it, but I would also welcome any math/logic to calculate it and eventually turn it into code.


Simon Fraser February 2016

Have you tried the ipaddress module? It comes with Python 3, but is installable for Python 2.

import ipaddress
startip = ipaddress.IPv4Address('')
endip = ipaddress.IPv4Address('')
# summarize_address_range produces a generator, so force the results
networks = [n for n in ipaddress.summarize_address_range(startip, endip)]
# [IPv4Network('')] 

Robᵩ February 2016

It looks like netaddr.spanning_cidr does the trick:

In [5]: netaddr.spanning_cidr(['', ''])
Out[5]: IPNetwork('')

Post Status

Asked in February 2016
Viewed 1,452 times
Voted 8
Answered 2 times


Leave an answer

Quote of the day: live life