ipaddress - IPv4/IPv6 Manipulation Library
The `ipaddress` module provides comprehensive tools for creating, manipulating, and operating on IPv4 and IPv6 addresses and networks. It is part of the Python 3 standard library (since Python 3.3) and available as a backport on PyPI for older Python versions. It simplifies common networking tasks such as IP address and network validation, subnetting, network relationship checks, and host enumeration.
Warnings
- gotcha The `ipaddress` module on PyPI is a backport of the standard library module. For Python 3.3 and newer, `ipaddress` is built-in and does not require installation via pip. Ensure you are using the appropriate version for your Python environment.
- breaking The `ipaddr` library is an older, superseded project that has API differences from `ipaddress`. While it served a similar purpose, it has been officially superseded by `ipaddress`.
- gotcha When creating `IPv4Network` or `IPv6Network` objects, the host portion of the address must be all zeroes by default (strict mode). If you provide a host address in a network definition, a `ValueError` will be raised unless `strict=False` is passed. Even with `strict=False`, the host bits will be silently zeroed out to form a network address. For representing an address *and* its prefix (like an interface address), use `IPv4Interface` or `IPv6Interface`.
- gotcha In Python 2 environments using the `ipaddress` backport, there are nuances with string and byte types. Textual IP addresses should often be `unicode` strings, and packed (binary) representations might use `bytearray` instead of Python 3's distinct `bytes` type. This can lead to unexpected behavior if not handled carefully during Python 2/3 migration or interoperability.
Install
-
pip install ipaddress -
# ipaddress is built-in since Python 3.3, no installation needed.
Imports
- ipaddress
import ipaddress
Quickstart
import ipaddress
# Validate and parse an IP address
ipv4_addr = ipaddress.ip_address('192.168.1.1')
print(f"IPv4 Address: {ipv4_addr}, Version: {ipv4_addr.version}, Is private: {ipv4_addr.is_private}")
ipv6_addr = ipaddress.ip_address('2001:db8::1')
print(f"IPv6 Address: {ipv6_addr}, Version: {ipv6_addr.version}, Is global: {ipv6_addr.is_global}")
# Define and inspect an IP network
network = ipaddress.ip_network('192.168.1.0/24')
print(f"Network: {network}")
print(f"Number of hosts: {network.num_addresses}")
print(f"Network address: {network.network_address}")
print(f"Broadcast address: {network.broadcast_address}")
# Check if an address is in a network
host_in_network = ipaddress.ip_address('192.168.1.50')
print(f"{host_in_network} in {network}: {host_in_network in network}")
# Iterate over hosts in a network
# for host in network.hosts():
# print(host)
# Subnetting
supernet = ipaddress.ip_network('10.0.0.0/8')
for subnet in supernet.subnets(prefixlen_diff=2):
print(f"Subnet: {subnet}")