Python 3:从CIDR表示法生成可能的IP地址列表

33 投票
8 回答
96965 浏览
提问于 2025-04-15 17:15

我被分配了一个任务,要用Python(3.1)写一个函数,这个函数可以接收CIDR表示法,并返回可能的IP地址列表。我在python.org上查了一下,找到了这个链接:http://docs.python.org/dev/py3k/library/ipaddr.html

但是我没有找到能满足这个需求的内容……如果有人能提供帮助,我会非常感激。提前谢谢大家。:-)

8 个回答

15

我宁愿做点数学运算,也不想安装额外的模块,难道就没有人和我一样吗?

#!/usr/bin/env python
# python cidr.py 192.168.1.1/24

import sys, struct, socket

(ip, cidr) = sys.argv[1].split('/')
cidr = int(cidr) 
host_bits = 32 - cidr
i = struct.unpack('>I', socket.inet_aton(ip))[0] # note the endianness
start = (i >> host_bits) << host_bits # clear the host bits
end = start | ((1 << host_bits) - 1)

# excludes the first and last address in the subnet
for i in range(start, end):
    print(socket.inet_ntoa(struct.pack('>I',i)))
51

如果你不一定要使用内置的模块,有一个叫做 netaddr 的项目,这是我用过的最好的处理IP网络的模块。

你可以看看这个 IP教程,它展示了处理网络和识别IP地址是多么简单。这里有个简单的例子:

>>> from netaddr import IPNetwork
>>> for ip in IPNetwork('192.0.2.0/23'):
...    print '%s' % ip
...
192.0.2.0
192.0.2.1
192.0.2.2
192.0.2.3
...
192.0.3.252
192.0.3.253
192.0.3.254
192.0.3.255
79

在Python 3中,这个操作非常简单

>>> import ipaddress
>>> [str(ip) for ip in ipaddress.IPv4Network('192.0.2.0/28')]
['192.0.2.0', '192.0.2.1', '192.0.2.2',
'192.0.2.3', '192.0.2.4', '192.0.2.5',
'192.0.2.6', '192.0.2.7', '192.0.2.8',
'192.0.2.9', '192.0.2.10', '192.0.2.11',
'192.0.2.12', '192.0.2.13', '192.0.2.14',
'192.0.2.15']

撰写回答