MoMoney February 2016

Python Lowest Common CIDR

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

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.

Answers


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('63.223.64.0')
endip = ipaddress.IPv4Address('63.223.127.255')
# summarize_address_range produces a generator, so force the results
networks = [n for n in ipaddress.summarize_address_range(startip, endip)]
print(networks)
# [IPv4Network('63.223.64.0/18')] 


Robᵩ February 2016

It looks like netaddr.spanning_cidr does the trick:

In [5]: netaddr.spanning_cidr(['63.223.64.0', '63.223.127.255'])
Out[5]: IPNetwork('63.223.64.0/18')

Post Status

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

Search




Leave an answer