Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Detect Network Interface Changes in Python

Monitor active network interfaces and print a message when an interface is added or removed using psutil and socket.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Requires third-party packages — install first
pip install psutil

Python code

35 lines
Python 3.9+
import socket
import psutil
import time

def get_network_interfaces():
    """Return a set of currently active interface names."""
    active_ifaces = set()
    for iface, addrs in psutil.net_if_addrs().items():
        for addr in addrs:
            if addr.family == socket.AF_INET:  # IPv4 address present
                active_ifaces.add(iface)
                break
    return active_ifaces

def monitor_interface_changes(interval=2):
    print(f"Monitoring network interface changes every {interval}s. Press Ctrl+C to stop.")
    prev = get_network_interfaces()
    print(f"Initial interfaces: {prev}")
    try:
        while True:
            time.sleep(interval)
            current = get_network_interfaces()
            if current != prev:
                added = current - prev
                removed = prev - current
                if added:
                    print(f"[+] Interface added: {added}")
                if removed:
                    print(f"[-] Interface removed: {removed}")
                prev = current
    except KeyboardInterrupt:
        print("\nMonitoring stopped.")

if __name__ == "__main__":
    monitor_interface_changes()

Output

stdout
Monitoring network interface changes every 2s. Press Ctrl+C to stop.
Initial interfaces: {'eth0', 'wlan0', 'lo'}
[+] Interface added: {'eth1'}
[-] Interface removed: {'eth0'}

Monitoring stopped.

How it works

This script uses psutil.net_if_addrs() to fetch all network interfaces and checks each address family with socket.AF_INET to identify IPv4-enabled interfaces. By comparing the current set of active interfaces with the previous set on each loop iteration, it detects additions and removals. The script keeps running until interrupted via Ctrl+C, making it suitable for live network monitoring. The use of time.sleep(interval) controls the polling frequency without consuming excessive CPU.

Common mistakes

  • Forgetting to install psutil with `pip install psutil` before running the script.
  • Filtering by IPv4 only — virtual or IPv6-only interfaces may be missed if the code is not adjusted.
  • Not handling permissions: on some systems, psutil may require elevated privileges to access all interface details.

Variations

  1. Use `asyncio` with `asyncio.sleep` for non-blocking monitoring in async applications.
  2. Extend the script to send an email or Slack notification when a change is detected using `smtplib` or `requests`.

Real-world use cases

  • Automatically logging when a VPN interface connects or disconnects on a remote server.
  • Triggering a network configuration reload in a container orchestration tool when interfaces change.
  • Alerting a user when a USB network adapter is plugged in or unplugged on a laptop.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.