lovetocode
lovetocode

Reputation: 31

Python: List of addressable IP addresses

What's the most Pythonic way to create a list of the addressable IP addresses given a netaddr IPRange or netaddr IPNetwork.

If I use these, then it includes subnet and broadcast addresses:

hosts = list(IPRange('212.55.64.0','212.55.127.255'))
hosts = IPNetwork('192.168.0.1/24')

So what I need for say IPNetwork(192.168.0.0/27) is a list from 192.168.0.1 to 192.168.0.31 note that 192.168.0.0 and 192.168.0.32 must not be included.

EDIT

Thanks for info on how to do it with IPy. Does anybody know if it can be done with netaddr?

Upvotes: 3

Views: 2561

Answers (2)

user1662701
user1662701

Reputation: 21

The following is a quick script to do what you want using netaddr
(Python 2.7, linux)

from netaddr import *

def addr(address, prefix):
    ip = IPNetwork(address)
    ip.prefixlen = int(prefix)
    return ip

myip = addr('192.168.0.0', '27')

for usable in myip.iter_hosts():
    print '%s' % usable

Upvotes: 1

lovetocode
lovetocode

Reputation: 31

After doing a bit of research I found this way:

 l = list(netaddr.IPNetwork('192.168.0.0/27').iter_hosts())

Upvotes: 0

Related Questions