Warm tip: This article is reproduced from serverfault.com, please click

python-如何使用ipaddr模块获取CIDR的第一个/最后一个IP地址

(python - How to get first/last IP address of CIDR using ipaddr module)

发布于 2016-11-01 21:19:30

蛮力方法:

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))))
Questioner
aaa90210
Viewed
11
kiwi_gem81 2016-11-02 05:45:09

也许改为尝试netaddr,尤其是索引部分。

https://pythonhosted.org/netaddr/tutorial_01.html#indexing

from netaddr import *
import pprint

ip = IPNetwork('10.10.128.0/17')

print "ip.cidr = %s" % ip.cidr
print "ip.first.ip = %s" % ip[0]
print "ip.last.ip = %s" % ip[-1]