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.
pip install psutil
Python code
35 linesimport 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
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
- Use `asyncio` with `asyncio.sleep` for non-blocking monitoring in async applications.
- 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
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.