Python 3.3+ipaddressterm
ipaddress
module
Parses and validates IPv4 and IPv6 addresses and networks: subnet membership, host iteration, masks.
Syntax
import ipaddress
Use ipaddress instead of parsing address strings with a regular expression: it checks octet ranges itself, understands IPv6 and tells you whether an address lies in a network. An address (ip_address) and a network (ip_network) are different objects: '10.0.0.0/8' is a network, while ip_network('10.0.0.5/8') raises ValueError because host bits are set; pass strict=False or use ip_interface instead.
Examples
import ipaddress
net = ipaddress.ip_network('192.168.1.0/30')
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(ipaddress.ip_address('::1').version) # → 6
ipaddress.ip_network('10.0.0.5/8') # → ValueError: host bits set
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy