使用Python检测可用的网络适配器

2024-05-14 18:45:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检测连接到DHCP并从中获得IP的可用网络接口。我使用以下脚本生成可用适配器的列表。在

import psutil
addrs = psutil.net_if_addrs()
all_network_interfaces = addrs.keys()
available_networks = []
for value in all_network_interfaces:
    if addrs[value][1][1].startswith("169.254"):
        continue
    else:
        available_networks.append(value)
print(available_networks)

从169.254开始的是使用自动专用IP寻址(APIPA)的适配器,因此我要过滤掉它们。当我用以太网线连接时,这个脚本显示了相关的适配器,如果我还在连接以太网时通过WiFi连接,它会将WiFi添加到列表中。但是,在断开WiFi连接后,WiFi适配器仍然保留IP,并且仍然存在于列表中。我想是我的适配卡有问题(可能是功能)。什么是最好的方法绕过这一点,只获得与DHCP连接的适配器?在


Tags: ip脚本列表ifvaluenetworkall适配器
2条回答

使用^{}只需启动并运行网络接口:

import psutil

addresses = psutil.net_if_addrs()
stats = psutil.net_if_stats()

available_networks = []
for intface, addr_list in addresses.items():
    if any(getattr(addr, 'address').startswith("169.254") for addr in addr_list):
        continue
    elif intface in stats and getattr(stats[intface], "isup"):
        available_networks.append(intface)

print(available_networks)

样本输出:

^{pr2}$

有一个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'}}

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

相关问题 更多 >

    热门问题