Reputation: 1214
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.
Upvotes: 1
Views: 896
Reputation: 168626
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')
Upvotes: 1
Reputation: 2818
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')]
Upvotes: 3