Python: check whether a network interface is up
The interface can be configured with an IP address and not be up so the accepted answer is wrong. You actually need to check /sys/class/net/<interface>/flags
. If the content is in the variable flags, flags & 0x1
is whether the interface is up or not.
Depending on the application, the /sys/class/net/<interface>/operstate
might be what you really want, but technically the interface could be up and the operstate
down, e.g. when no cable is connected.
All of this is Linux-specific of course.
Answer using psutil:
import psutil
import socket
def check_interface(interface):
interface_addrs = psutil.net_if_addrs().get(interface) or []
return socket.AF_INET in [snicaddr.family for snicaddr in interface_addrs]
With pyroute2.IPRoute:
from pyroute2 import IPRoute
ip = IPRoute()
state = ip.get_links(ip.link_lookup(ifname='em1'))[0].get_attr('IFLA_OPERSTATE')
ip.close()
With pyroute2.IPDB:
from pyroute2 import IPDB
ip = IPDB()
state = ip.interfaces.em1.operstate
ip.release()
As suggested by @Gabriel Samfira, I used netifaces
. The following function returns True when an IP address is associated to a given interface.
def is_interface_up(interface):
addr = netifaces.ifaddresses(interface)
return netifaces.AF_INET in addr
The documentation is here