ifaddr Library
ifaddr is a small, cross-platform Python library designed for enumerating network interfaces and their associated IP addresses. It supports Linux, OS X, Windows, and is expected to work on other BSD derivatives and Solaris/Illumos. Released under the MIT License, the current version 0.2.0 (June 2022) works with Python 3.9+ and requires no compilation, simplifying installation.
Warnings
- breaking Version 0.2.0 dropped support for Python 3.6.
- gotcha By default, `ifaddr.get_adapters()` only returns interfaces with configured IP addresses. To include interfaces without any assigned IP, pass `include_unconfigured=True`.
- gotcha For IPv6 addresses, the `ip.ip` attribute returns a three-tuple: `(ip_address_string, flowinfo, scope_id)`, not just a string, which might require unpacking or specific handling.
- gotcha On Windows, the `adapter.name` property returns a UUID string, not a human-readable name. Use `adapter.nice_name` for a more descriptive identifier.
- gotcha While `ifaddr` is lightweight and doesn't require compilation, the `netifaces` library offers more comprehensive network interface information. As of `ifaddr` 0.2.0, an equivalent to `netifaces.interfaces()` is available at `ifaddr.netifaces.interfaces()`.
Install
-
pip install ifaddr
Imports
- get_adapters
import ifaddr adapters = ifaddr.get_adapters()
Quickstart
import ifaddr
# Get all network adapters
adapters = ifaddr.get_adapters()
for adapter in adapters:
print(f"IPs of network adapter {adapter.nice_name}")
if adapter.ips:
for ip in adapter.ips:
# ip.ip will be a string for IPv4, and a tuple (ip_str, flowinfo, scope_id) for IPv6
print(f" {ip.ip}/{ip.network_prefix}")
else:
print(" No IPs configured")
# To include interfaces without configured IP addresses:
# adapters_with_unconfigured = ifaddr.get_adapters(include_unconfigured=True)