aaa90210 aaa90210 - 10 months ago 80
Python Question

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

The brute force approach:

from ipaddr import IPv4Network
n = IPv4Network('')
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))))

Answer Source

Maybe try netaddr instead, in particular the indexing section.

from netaddr import *
import pprint

ip = IPNetwork('')

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