Portable Network Interface Information
netifaces is a Python library that provides a portable way to access network interface information, including IP addresses, netmasks, broadcast addresses, and gateway details. It supports various operating systems such as OS X, Linux, and Windows. The current version is 0.11.0, but the original project is no longer actively maintained. Forks exist to provide continued support and new features.
Warnings
- deprecated The original `netifaces` library (version 0.11.0 and earlier) is no longer actively maintained by its original author (al45tair) since at least May 2021. This means no new features, official bug fixes, or updates for newer Python versions are expected for this package. Users needing active development or support for modern Python versions should consider actively maintained forks like `netifaces2` or `netifaces-plus`.
- gotcha The numeric values of address family constants (e.g., `netifaces.AF_INET`, `netifaces.AF_LINK`) are system-dependent and can vary across different operating systems or even kernel versions. Do not assume fixed integer values or interchange them directly with constants from Python's `socket` module, as their underlying values might differ.
- gotcha The output of `netifaces.ifaddresses(interface_name)` is a dictionary keyed by system-dependent address family integers. Each value is a list of dictionaries, where each inner dictionary represents an address. This nested structure can appear cryptic and requires careful parsing, as a single interface can have multiple addresses of the same family.
- gotcha Installing `netifaces` from source distribution (e.g., a `.tar.gz` file or directly from GitHub without pre-compiled wheels) requires platform-specific development tools, including a C compiler and Python development headers. Missing these tools will result in compilation errors during installation.
- gotcha On Windows, the `netifaces` library (version 0.11.0) might not report IPv4 addresses for network interfaces that have static IP configurations but are currently in a 'down' state. IPv6 addresses are generally reported regardless of interface status.
Install
-
pip install netifaces
Imports
- netifaces
import netifaces
Quickstart
import netifaces
# Get a list of all network interface names
interfaces = netifaces.interfaces()
print(f"Interfaces: {interfaces}")
# Get addresses for a specific interface (e.g., the first one found)
if interfaces:
first_interface = interfaces[0]
addresses = netifaces.ifaddresses(first_interface)
print(f"Addresses for {first_interface}:\n{addresses}")
# Example: Accessing IPv4 addresses if available
if netifaces.AF_INET in addresses:
ipv4_addresses = addresses[netifaces.AF_INET]
print(f"IPv4 addresses on {first_interface}: {ipv4_addresses}")
# Get default gateway information
gateways = netifaces.gateways()
print(f"Gateways: {gateways}")