10

In Python, is there a way to detect whether a given network interface is up?

In my script, the user specifies a network interface, but I would like to make sure that the interface is up and has been assigned an IP address, before doing anything else.

I'm on Linux and I am root.

Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185

6 Answers6

14

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.

user18197
  • 386
  • 1
  • 4
  • 6
  • 2
    A warning: in Linux Mint 18.2, the Cinnamon Network Manager applet control to turn off a network adapter leaves it both UP and operational. It removes the IP address, though. – Harvey Feb 21 '18 at 18:29
10

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

Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185
  • 1
    A useful check before calling the above function is: `if anInterface in netifaces.interfaces() #...` – Ricky Robinson Jul 16 '13 at 19:52
  • 2
    Unfortunately, this does work only half for IPv6/AF_INET6: while an interface becomming RUNNING gets its LLA, when the same interface goes offline, the LLA still lives on. – TheDiveO Jul 25 '17 at 15:36
7

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]
ofirule
  • 4,233
  • 2
  • 26
  • 40
3

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()
svinota
  • 779
  • 8
  • 10
2

You can see the content of the file in /sys/class/net/<interface>/operstate. If the content is not down then the interface is up.

André Pires
  • 91
  • 1
  • 4
0

If the question is about checking if the cable is conencted (FreeBSD);

[status for status in run.cmd(' /usr/local/bin/sudo ifconfig %s ' % interface).split("\t") if status.strip().startswith("status")][0].strip().endswith("active")

For this, no api support so far :( ...

myuce
  • 1,321
  • 1
  • 19
  • 29