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 psutilListing 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:")
for iface in netifaces.interfaces():
print(f" - {iface}")
if __name__ == "__main__":
list_interfaces()Output (Example):
Network Interfaces Found:
- lo
- eth0
- wlan0
- docker0Retrieving 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:
addrs = netifaces.ifaddresses(interface)
print(f"\nDetails for {interface}:")
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')}")
if netifaces.AF_LINK in addrs:
mac_info = addrs[netifaces.AF_LINK][0]
print(f" MAC Address: {mac_info.get('addr')}")
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.")
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: ::1Monitoring 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...")
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)
stats_end = psutil.net_io_counters(pernic=True)[interface]
bytes_sent = stats_end.bytes_sent - stats_start.bytes_sent
bytes_recv = stats_end.bytes_recv - stats_start.bytes_recv
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")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.