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

How to get first/last IP address of CIDR using ipaddr module

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

The brute force approach:

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

I was wondering how I would get the first and last IP address from a CIDR without having to iterate over a potentially very large list to get the first and last element?

I want this so I can then generate a random ip address in this range using something like this:

socket.inet_ntoa(struct.pack('>I', random.randint(int(first),int(last))))
Questioner
aaa90210
Viewed
0
kiwi_gem81 2016-11-02 05:45:09

Maybe try netaddr instead, in particular the indexing section.

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]