Python最低常见CIDR

时间:2016-02-08 16:06:09

标签: python ip subnet cidr

假设我有两个IP:startip = '63.223.64.0'endip = '63.223.127.255'

我知道在python netaddr.iprange_to_cidrs(startip, endip)中会给你一个恰好适合边界的CIDR子网列表。但是,我希望选择一个 CIDR子网来覆盖它,即使它提供了更多的IP。

我更喜欢这样做的功能,但我也欢迎任何数学/逻辑来计算它并最终将其转换为代码。

2 个答案:

答案 0 :(得分:3)

您是否尝试过ipaddress模块?它附带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')] 

答案 1 :(得分:1)

看起来netaddr.spanning_cidr可以解决问题:

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