Search code examples
pythonnetworkingipdhcpnetwork-interface

Python: check whether a network interface is up


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.


Solution

  • 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