蛮力法:
from ipaddr import IPv4Network
n = IPv4Network('10.10.128.0/17')
all = list(n.iterhosts()) # will give me all hosts in network
first,last = all[0],all[-1] # first and last IP
我想知道如何从 CIDR 获取第一个和最后一个 IP 地址,而不必遍历一个可能非常大的列表来获取第一个和最后一个元素?
我想要这个,这样我就可以使用这样的东西在这个范围内生成一个随机的 ip 地址:
socket.inet_ntoa(struct.pack('>I', random.randint(int(first),int(last))))
请您参考如下方法:
从 Python 3.3 开始,您可以使用 ipaddress module
你可以这样使用它:
import ipaddress
n = ipaddress.IPv4Network('10.10.128.0/17')
first, last = n[0], n[-1]
__getitem__ 已实现,因此不会生成任何大列表。
https://github.com/python/cpython/blob/3.6/Lib/ipaddress.py#L634
