简体   繁体   中英

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.

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')] 

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM