Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 235
Ricky Robinson Avatar asked Jul 16 '13 14:07

Ricky Robinson


People also ask

How can I tell which network interface is being used?

Open up the Task Manager, go to the Networking tab, and you can see which adapters are being utilized. Save this answer. Show activity on this post. You can identify the adapter by MAC address (Physical Address) using the ipconfig /all command.

Which command will show the status of Ethernet interface eth0?

ifconfig command – It is used to display or configure a network interface.


1 Answers

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

like image 91
Ricky Robinson Avatar answered Oct 16 '22 17:10

Ricky Robinson