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!
Log in to the system as root and run ifconfig -a plumb in a command shell. The command discovers all installed network interfaces.
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.
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.
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With