在Python中给定IPv4地址列表,得到最小的网络

2024-05-16 03:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.6.6,不允许我更改它。我有一个IPv4地址的分类列表。我需要找到覆盖列表中所有ip地址的最小网络。最小的网络可以是CIDR,也可以是带有子网掩码的网络地址。我还没有找到使用netaddr模块的简单方法。以下是示例:

x=['192.168.0.0', '192.168.2.245', '192.168.255.255']
cidr = get_cidr_for_addresses(x)
print cidr ##should print '192.168.0.0/16'

Tags: 模块方法ip网络示例列表get地址
2条回答
# Baseline IP
tmp = 19216800

# List of IPS
x=['192.168.0.0', '192.168.2.245', '192.168.255.255']

# Loop Through each item in list
for item in x:
    # Split on the period
    split = item.split('.')

    # Convert to number
    tp = int(split[0] + split[1] + split[2] + split[3])

    # Compare and set
    if tp < tmp: 
        tmp = tp

print tmp

又快又脏。:天

这似乎正是netaddr.spanning_cidr的作用。在

$ python
Python 2.7.9rc1 (default, Dec 10 2014, 10:58:16)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import netaddr
>>> x = netaddr.spanning_cidr(['192.168.0.0', '192.168.2.245', '192.168.255.255'])
>>> print x
192.168.0.0/16
>>> print type(x)
<class 'netaddr.ip.IPNetwork'>

相关问题 更多 >