ipaddress.ip_network, collapse_addresses, and address comparison
ipaddress.ip_address(address)
ipaddress.ip_network(address, strict=True)
ipaddress.collapse_addresses(addresses)Reject a strict network with host bits set, collapse two halves of 192.0.2.0/24, and show same-version versus mixed-version comparison.
| Parameter | Description |
|---|---|
address | A string or integer address, or a network in CIDR form. The values here are documentation ranges only. |
strict | When True (the default), a network string must have host bits clear. When False, host bits are masked off. |
Returns: ip_address returns an IPv4Address or IPv6Address. ip_network returns a network. collapse_addresses yields merged networks.
Raises
ValueError— Raised when a strict network has host bits set, or when the text is not a valid address or network.TypeError— Raised when IPv4 and IPv6 addresses are compared to each other.
- These calls only parse strings. They do not open sockets.
import ipaddress
try:
ipaddress.ip_network("192.0.2.1/24")
except ValueError as exc:
print(type(exc).__name__)
print(ipaddress.ip_network("192.0.2.1/24", strict=False))
print(list(ipaddress.collapse_addresses([
ipaddress.ip_network("192.0.2.0/25"),
ipaddress.ip_network("192.0.2.128/25"),
])))
print(ipaddress.ip_address("192.0.2.1") < ipaddress.ip_address("192.0.2.2"))
try:
ipaddress.ip_address("192.0.2.1") < ipaddress.ip_address("2001:db8::1")
except TypeError as exc:
print(type(exc).__name__)Expected output
ValueError
192.0.2.0/24
[IPv4Network('192.0.2.0/24')]
True
TypeError