How to get Network Interface Card names in Python?

Question:

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 code to get IP addresses and MAC addresses only such as

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

Advice on the code would really be appreciated.

Asked By: JavaNoob

||

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.

Answered By: Arlaharen

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.

Answered By: Kristian Evensen

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)
Answered By: nihiser

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.

Answered By: David Breuer

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.

Answered By: tijko

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/')
Answered By: André Pires

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())
Answered By: andrew

There is a python package get-nic which gives NIC status, updown, 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

Answered By: pradpi

socket module in Python >= 3.3:

import socket

# Return a list of network interface information
socket.if_nameindex()

https://docs.python.org/3/library/socket.html#socket.if_nameindex

Answered By: yang5
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.