简体   繁体   中英

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?

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

IPY

经过一番研究后我发现了这种方式:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM