Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Network Interface Card names in Python?

I am totally new to python programming so please be patient with me.

Is there anyway to get the names of the NIC cards in the machine etc. eth0, lo? If so how do you do it?

I have researched but so far I have only found codes to get IP addresses and MAC addresses only such as

import socket socket.gethostbyname(socket.gethostname()) 

Advice on the codes would really be appreciated. Thanks!

like image 978
JavaNoob Avatar asked Oct 01 '10 06:10

JavaNoob


People also ask

How do I find my network interface name?

Log in to the system as root and run ifconfig -a plumb in a command shell. The command discovers all installed network interfaces.

How do I find the interface list?

You can launch a command prompt by pressing "Windows Key-R," typing "cmd" and pressing "Enter." Select the command prompt window, type the command "route print" and press "Enter" to display the "Interface List" and system routing tables.

Which command would you run to find the name of your network interface card?

To do this, simply open a terminal and type “ifconfig -a”. This will return a list of all available network interfaces on your system. You can append the name of the interface to the end of the command (e.g. “ifconfig eth0”) to view information about a specific interface.


2 Answers

On Linux, you can just list the links in /sys/class/net/ by

os.listdir('/sys/class/net/') 

Not sure if this works on all distributions.

like image 120
David Breuer Avatar answered Sep 21 '22 06:09

David Breuer


A great Python library I have used to do this is psutil. It can be used on Linux, Windows, and OSX among other platforms and is supported from Python 2.6 to 3.6.

Psutil provides the net_if_addrs() function which returns a dictionary where keys are the NIC names and value is a list of named tuples for each address assigned to the NIC which include the address family, NIC address, netmask, broadcast address, and destination address.

A simple example using net_if_addrs() which will print a Python list of the NIC names:

import psutil  addrs = psutil.net_if_addrs() print(addrs.keys()) 
like image 30
andrew Avatar answered Sep 21 '22 06:09

andrew