netaddr: Network Address Manipulation Library
netaddr is a Python library for manipulating network addresses, subnets, MAC addresses, and related network concepts. It supports IPv4, IPv6, EUI (MAC addresses), OUI, and IAB objects, providing a rich API for parsing, validating, converting, and performing operations like aggregation, intersection, and iteration. The current version is 1.3.0, and it maintains an active, albeit irregular, release cadence.
Warnings
- breaking The handling of RFC 6164 IPv6 point-to-point subnets changed. `netaddr` no longer reserves the first IP address, affecting `num_hosts` and address iteration for these specific subnets.
- breaking The `is_loopback` property for `IPNetwork('::1/128')` (and similar IPv6 loopback representations) now correctly returns `True`. Prior versions returned `False`.
- gotcha While core `IPAddress` and `IPNetwork` objects are generally treated as immutable once created, some operations on `IPSet` are in-place, and certain properties like `IPNetwork.netmask` can be reassigned. Be aware of mutable vs. immutable behavior.
- gotcha Operations often expect specific `netaddr` object types (`IPAddress`, `IPNetwork`, `EUI`). Passing raw strings or incompatible types can lead to errors. Always explicitly convert when necessary.
Install
-
pip install netaddr
Imports
- IPAddress
from netaddr import IPAddress
- IPNetwork
from netaddr import IPNetwork
- IPSet
from netaddr import IPSet
- EUI
from netaddr import EUI
- mac_unix_common
from netaddr.formatters import mac_unix_common
Quickstart
from netaddr import IPNetwork, IPAddress, EUI
# --- IP Network and Address Manipulation ---
ip_net = IPNetwork('192.168.0.0/24')
print(f"\nNetwork: {ip_net} (version {ip_net.version})")
print(f"Number of hosts: {ip_net.num_hosts}")
print(f"First usable address: {ip_net.first}")
print(f"Last usable address: {ip_net.last}")
# Iterate through hosts (excluding network and broadcast addresses)
print("First 3 hosts in network:")
for i, ip in enumerate(ip_net.hosts()):
if i >= 3:
break
print(f" - {ip}")
# Check if an IP is within a network
ip_addr = IPAddress('192.168.0.10')
print(f"Is {ip_addr} in {ip_net}? {ip_addr in ip_net}")
# --- MAC Address (EUI) Manipulation ---
mac = EUI('00-01-02-03-04-05')
print(f"\nMAC Address: {mac}")
print(f"MAC as integer: {int(mac)}")
print(f"Vendor prefix (OUI): {mac.oui}")
# Generate a different format
print(f"MAC in Cisco format: {mac.format(dialect='cisco')}")