简体   繁体   English

Python最低通用CIDR

[英]Python Lowest Common CIDR

Say I have two IPs: startip = '63.223.64.0' and endip = '63.223.127.255' 假设我有两个IP: startip = '63.223.64.0'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. 我了解在python中, netaddr.iprange_to_cidrs(startip, endip)将为您提供恰好在边界之间的CIDR子网列表。 However, I was hoping to go for one CIDR subnet that covers it all even if it gives a few more IPs. 但是,我希望能找到一个涵盖所有内容的CIDR子网,即使它提供了更多的IP。

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? 您是否尝试过ipaddress模块? It comes with Python 3, but is installable for Python 2. 它随Python 3一起提供,但可为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: 看起来netaddr.spanning_cidr可以解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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