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!

Answers


I don't think there's anything in the standard library to query these names.

If I needed these names on a Linux system I would parse the output of ifconfig or the contents of /proc/net/dev. Look at this blog entry for a similar problem.


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())

Since this answer pops up in Google when I search for this information, I thought I should add my technique for getting the available interfaces (as well as IP addresses). The very nice module netifaces takes care of that, in a portable manner.


Using python's ctypes you can make a call to the C library function getifaddrs:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from ctypes import *

class Sockaddr(Structure):
    _fields_ = [('sa_family', c_ushort), ('sa_data', c_char * 14)]

class Ifa_Ifu(Union):
    _fields_ = [('ifu_broadaddr', POINTER(Sockaddr)),
                ('ifu_dstaddr', POINTER(Sockaddr))]

class Ifaddrs(Structure):
    pass

Ifaddrs._fields_ = [('ifa_next', POINTER(Ifaddrs)), ('ifa_name', c_char_p),
                    ('ifa_flags', c_uint), ('ifa_addr', POINTER(Sockaddr)),
                    ('ifa_netmask', POINTER(Sockaddr)), ('ifa_ifu', Ifa_Ifu),
                    ('ifa_data', c_void_p)]


def get_interfaces():
    libc = CDLL('libc.so.6')
    libc.getifaddrs.restype = c_int
    ifaddr_p = pointer(Ifaddrs())
    ret = libc.getifaddrs(pointer((ifaddr_p)))
    interfaces = set()
    head = ifaddr_p
    while ifaddr_p:
        interfaces.add(ifaddr_p.contents.ifa_name)
        ifaddr_p = ifaddr_p.contents.ifa_next
    libc.freeifaddrs(head) 
    return interfaces

if __name__ == "__main__":
    print(get_interfaces())

Do note though this method is not portable.


To add to what @Kristian Evensen's mentions, here is what I used for a problem i was having. If you are looking to just get a list of the interfaces, use:

interface_list = netifaces.interfaces()

If you are wanting a specific interface, but don't know what the number at the end is (ie: eth0), use:

interface_list = netifaces.interfaces()
interface = filter(lambda x: 'eth' in x,interface_list)

Like David Breuer say, you can just list the directory "/ sys / class / net" on Linux. (It works on Fedora at least). If you need detailled information about some interface you can navigate on the intefaces's directories for more.

def getAllInterfaces():
    return os.listdir('/sys/class/net/')

There is a python package get-nic which gives NIC status, up\down, ip addr, mac addr etc

pip install get-nic

from get_nic import getnic

getnic.interfaces()

Output: ["eth0", "wlo1"]

interfaces = getnic.interfaces()
getnic.ipaddr(interfaces)

Output: 
{'lo': {'state': 'UNKNOWN', 'inet4': '127.0.0.1/8', 'inet6': '::1/128'}, 'enp3s0': {'state': 'DOWN', 'HWaddr': 'a4:5d:36:c2:34:3e'}, 'wlo1': {'state': 'UP', 'HWaddr': '48:d2:24:7f:63:10', 'inet4': '10.16.1.34/24', 'inet6': 'fe80::ab4a:95f7:26bd:82dd/64'}}

Refer GitHub page for more information: https://github.com/tech-novic/get-nic-details


Need Your Help

Jquery: Get value from dynamic attribute

jquery attributes

I’m adding a total amount value to a DIV through a jQuery Ajax call everytime I add a new item to a shopping cart. I need this value to be a part of a difference calculation (payment-totalAmount), ...

Handling orientation change in custom SplitViewController?

ios uiviewcontroller uiinterfaceorientation

I have written a custom SplitViewController which has a master (custom UITableView) and a detail view controller and this works perfectly in the landscape mode of the iPad.