如何在 Python 中获取网络接口卡名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3837069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:56:41  来源:igfitidea点击:

How to get Network Interface Card names in Python?

pythonnetworking

提问by JavaNoob

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

我对 python 编程完全陌生,所以请耐心等待。

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

有没有办法获得机器中网卡的名称等。 eth0,lo?如果是这样,你怎么做?

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

我已经研究过,但到目前为止我只找到了获取 IP 地址和 MAC 地址的代码,例如

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

Advice on the codes would really be appreciated. Thanks!

关于代码的建议将不胜感激。谢谢!

采纳答案by Arlaharen

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 ifconfigor the contents of /proc/net/dev. Look at this blog entryfor a similar problem.

如果我需要在Linux系统上这些名字我会分析的输出ifconfig或内容/proc/net/dev。查看此博客条目是否存在类似问题。

回答by Kristian Evensen

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 netifacestakes care of that, in a portable manner.

由于当我搜索此信息时此答案会在 Google 中弹出,因此我认为我应该添加获取可用接口(以及 IP 地址)的技术。非常好的模块netifaces以可移植的方式处理了这一点。

回答by nihiser

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:

为了补充@Kristian Evensen 提到的内容,这是我用于解决我遇到的问题的内容。如果您只想获取接口列表,请使用:

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:

如果您想要一个特定的接口,但不知道最后的数字是什么(即:eth0),请使用:

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

回答by David Breuer

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

在Linux上,你可以列出的链接/ SYS /班/网/通过

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

Not sure if this works on all distributions.

不确定这是否适用于所有发行版。

回答by tijko

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

使用 python,ctypes您可以调用 C 库函数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.

请注意,尽管此方法不可移植。

回答by André Pires

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.

就像 David Breuer 说的,你可以在 Linux 上列出目录“/sys/class/net”。(它至少适用于 Fedora)。如果您需要有关某些界面的详细信息,可以在界面目录中导航以获取更多信息。

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

回答by andrew

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.

我用来做这件事的一个很棒的 Python 库是psutil。它可以在 Linux、Windows 和 OSX 等平台上使用,并支持 Python 2.6 到 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.

Psutil 提供net_if_addrs()函数,该函数返回一个字典,其中键是 NIC 名称,值是分配给 NIC 的每个地址的命名元组列表,其中包括地址族、NIC 地址、网络掩码、广播地址和目标地址。

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

一个简单的例子net_if_addrs(),它将打印一个 NIC 名称的 Python 列表:

import psutil

addrs = psutil.net_if_addrs()
print(addrs.keys())

回答by pradpi

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

有一个 python 包 get-nic,它提供 NIC 状态、up\down、ip addr、mac addr 等


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

有关更多信息,请参阅 GitHub 页面:https: //github.com/tech-novic/get-nic-details

回答by yang5

socketmodule in Python >= 3.3:

socketPython 中的模块 >= 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

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