Python 3.3+ipaddressterm
ipaddress.IPv4Network
networks
The IPv4 network class: a network address and a mask; it lists hosts, tests address membership and splits into subnets.
Syntax
ipaddress.IPv4Network(address, strict=True)
num_addresses counts the network and broadcast addresses, while hosts() leaves them out: a /24 has 256 addresses but 254 hosts, yet for /31 and /32 hosts() returns every address. Test membership with in: an address of the other version gives False rather than an error. Like ip_network(), the constructor defaults to strict=True and rejects an address with host bits set.
Examples
import ipaddress
net = ipaddress.IPv4Network('192.168.1.0/30')
print(net.num_addresses, net.broadcast_address) # → 4 192.168.1.3
print([str(h) for h in net.hosts()]) # → ['192.168.1.1', '192.168.1.2']
print(ipaddress.ip_address('192.168.1.2') in net) # → True
print(list(ipaddress.IPv4Network('10.0.0.0/24').subnets(new_prefix=26))[1]) # → 10.0.0.64/26
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy