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.
Common errors
-
ModuleNotFoundError: No module named 'ifaddr'
cause The 'ifaddr' package is not installed in the Python environment where the code is being executed.fixInstall the 'ifaddr' package using pip: `pip install ifaddr` -
AttributeError: module 'ifaddr' has no attribute 'get_adapters'
cause The `get_adapters` function is either misspelled, or a local Python file named `ifaddr.py` is shadowing the installed 'ifaddr' package, causing Python to import the local file instead of the library.fixEnsure `ifaddr.get_adapters()` is spelled correctly. If a local file named `ifaddr.py` exists in your project directory, rename it to avoid conflicting with the installed library. The correct import and usage pattern is typically: `import ifaddr; adapters = ifaddr.get_adapters()`. -
AttributeError: 'ifaddr.IP' object has no attribute 'address'
cause Users attempting to access the IP address from an `ifaddr.IP` object often use a common attribute name like 'address', but the library exposes the IP address value via the 'ip' attribute.fixAccess the IP address using the `ip` attribute: `ip_object.ip` (e.g., `print(ip.ip)`).
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)