How to Configure and Monitor Network Interfaces in Python
Configuring and monitoring network interfaces programmatically is essential for system administration, DevOps automation, and building network diagnostic tools. Python makes this accessible through the netifaces library (for inspection) and psutil (for traffic monitoring).
This guide walks you through listing interfaces, retrieving IP/MAC details, and monitoring real-time traffic statistics.
Setting Up the Environment
Python does not have deep network interface inspection capabilities in its standard library. We need two external packages:
netifaces: For retrieving IP addresses, MAC addresses, and gateway info.psutil: For monitoring bytes sent/received and packet counts.
Installation:
pip install netifaces psutil
Listing Available Interfaces
The first step is identifying which interfaces (e.g., eth0, wlan0, lo) are present on the system.
import netifaces
def list_interfaces():
print("Network Interfaces Found:")
# netifaces.interfaces() returns a list of interface names
for iface in netifaces.interfaces():
print(f" - {iface}")
if __name__ == "__main__":
list_interfaces()
Output (Example):
Network Interfaces Found:
- lo
- eth0
- wlan0
- docker0
Retrieving Detailed Interface Information
Once you have an interface name, you can query its addresses. netifaces organizes information by "Address Families" (e.g., AF_INET for IPv4, AF_LINK for MAC).
Example: Get IP and MAC Addresses
import netifaces
def get_interface_details(interface):
try:
# Get all addresses for the interface
addrs = netifaces.ifaddresses(interface)
print(f"\nDetails for {interface}:")
# 1. Get IPv4 Address (AF_INET)
if netifaces.AF_INET in addrs:
ipv4_info = addrs[netifaces.AF_INET][0]
print(f" IPv4 Address: {ipv4_info.get('addr')}")
print(f" Netmask: {ipv4_info.get('netmask')}")
# 2. Get MAC Address (AF_LINK)
if netifaces.AF_LINK in addrs:
mac_info = addrs[netifaces.AF_LINK][0]
print(f" MAC Address: {mac_info.get('addr')}")
# 3. Get IPv6 Address (AF_INET6)
if netifaces.AF_INET6 in addrs:
ipv6_info = addrs[netifaces.AF_INET6][0]
print(f" IPv6 Address: {ipv6_info.get('addr')}")
except ValueError:
print(f"Error: Interface '{interface}' not found.")
# Usage: Check specific interface (e.g., 'eth0' or 'en0')
# Note: Replace 'lo' with your actual main interface name
get_interface_details('lo')
Output:
Details for lo:
IPv4 Address: 127.0.0.1
Netmask: 255.0.0.0
MAC Address: 00:00:00:00:00:00
IPv6 Address: ::1
On Windows, interface names look like {UUID-STRING}. On Linux/macOS, they are readable names like eth0 or en0.
Monitoring Network Traffic
Using psutil, you can measure bandwidth usage. Since psutil provides cumulative counters (total bytes since boot), calculating speed requires taking two snapshots.
Example: Real-Time Traffic Monitor
import psutil
import time
def monitor_traffic(interface, duration=5):
print(f"Monitoring {interface} for {duration} seconds...")
# Snapshot 1
# pernic=True separates stats by interface
stats_start = psutil.net_io_counters(pernic=True).get(interface)
if not stats_start:
print(f"Interface {interface} not found in statistics.")
return
time.sleep(duration)
# Snapshot 2
stats_end = psutil.net_io_counters(pernic=True)[interface]
# Calculate difference
bytes_sent = stats_end.bytes_sent - stats_start.bytes_sent
bytes_recv = stats_end.bytes_recv - stats_start.bytes_recv
# Calculate speed (Bytes per second)
speed_up = bytes_sent / duration
speed_down = bytes_recv / duration
print(f"--- Traffic Stats ---")
print(f"Upload: {speed_up / 1024:.2f} KB/s")
print(f"Download: {speed_down / 1024:.2f} KB/s")
print(f"Total Sent: {bytes_sent} bytes")
print(f"Total Recv: {bytes_recv} bytes")
# Usage
# Replace 'eth0' with your active network interface
# monitor_traffic('eth0')
To find your active interface dynamically for monitoring, you can inspect netifaces.gateways()['default'][netifaces.AF_INET][1].
Conclusion
To manage network interfaces in Python:
- Use
netifaces.interfaces()to list all available hardware ports. - Use
netifaces.ifaddresses(iface)to inspect configuration (IP, Subnet, MAC). - Use
psutil.net_io_counters()to monitor bandwidth and packet flow.