Search code examples
pythonip-addresscidr

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


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))))

Solution

  • 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]