Python 3:从CIDR表示法生成可能的IP地址列表
我被分配了一个任务,要用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)))
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']