PyQt6: 多网卡适配器的选择与显示(GPT4帮写)


(本文部分文案由ChatGPT生成,但代码均是Howie开发并验证通过,放心使用。)

另外,用GPT4生成的代码是调用socket API实现多网卡选择, 一如既往的测试运行报错,我就没在看,在最后面也把GPT output附上了,有兴趣的供参考吧~

1. 背景

在现代网络环境中,我们经常需要同时连接多个网络,例如公司内网和互联网。然而,大多数计算机只有一个默认网卡,这使得同时连接多个网络变得困难。因此,我们需要一种方法来选择使用哪个网卡连接网络。

Python 是一种非常强大的编程语言,可以用来编写网络应用程序。在本文中,我们将介绍如何使用 Python 编程实现多个网卡选择的功能,并通过PyQt6显示出来。


2. Python获取本机网卡适配器信息

这里使用了ifaddr, 是个好用切小巧能解决这类问题的lib

针对PyQt6显示,只需获取名称和获取相应的IP,我封装了两个API:

import ifaddr

def get_ethernet_adaptersList():
    adapters = ifaddr.get_adapters(include_unconfigured=False)
    return [adapter.nice_name for adapter in adapters[0:-1]]


def get_ip_address(interface_name):
    adapters = ifaddr.get_adapters()
    for adapter in adapters:
        if adapter.name == interface_name or adapter.nice_name == interface_name:
            for ip in adapter.ips:
                if ":" not in ip.ip[0]:  # only has ipv4
                    return ip.ip

    return "0.0.0.0"

测试打印获取到的本机网卡Name和IP:

 	ethernetList = get_ethernet_adaptersList()
    print(ethernetList)

    for i in range(len(ethernetList)):
        ip_adapter = get_ip_address(ethernetList[i])
        print(i, ethernetList[i], ip_adapter)

打印结果:

在这里插入图片描述


3. PyQT6 UI显示网卡信息

有了所有网卡的信息,我们就可以选择其中一个来连接网络。显示选择网卡的方法有很多种,例如使用固定的 IP 地址或者根据网络质量来选择。

在本文中,我们使用PyQT6界面作为UI显示:

打开QT Designer,简单做个comboBox 和Button来选择和刷新网卡:

在这里插入图片描述

Object信息:
在这里插入图片描述

接下来常规使用pyuic6 将.ui转成.py后,通过python显示出来:
在这里插入图片描述

在这里插入图片描述

4. PyQT6 后台处理:

Button

先给Button绑定个信号:

self.__ui.button_RefreshEthernet.clicked.connect(self.button_refresh_toggled_handler)

点击Button后,获取 list信息,更新到ComboBox即可:

这里小优化了一下:

  • 将list按名称排了下序
def button_refresh_toggled_handler(self):
    self.__ui.comboBox_EthernetList.clear()
    elist = get_ethernet_adaptersList()
    ethernetList = sorted(elist)
    for x in range(len(ethernetList)):
        print(x, ethernetList[x])
        self.__ui.comboBox_EthernetList.addItem(ethernetList[x])




# 获取hostIP:

```python
def get_host_ip() -> str:

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

启动运行,点击刷新网卡:
在这里插入图片描述

ComboBox

绑定信号:

 self.__ui.comboBox_EthernetList.activated[int].connect(self.ethernet_list_combobox_handler)

同时在ethernet_list_combobox_handler中,获取所选择的网卡信息和IP:

    def ethernet_list_combobox_handler(self, p_type):
        # self.adapter_select_index = p_type

        adapter_name = self.__ui.comboBox_EthernetList.currentText()

        adapter_ip = get_ip_address(adapter_name)

        print("selected adapter_ip:", adapter_name, adapter_ip)

在这里插入图片描述

Python使用多个网卡连接网络是一项非常重要的功能。我们可以根据实际需求来选择不同的网卡选择方法,以满足不同的应用场景。


附:GPT Output:

在这里插入图片描述
在这里插入图片描述


博主热门文章推荐:

在这里插入图片描述

一篇读懂系列:

LoRa Mesh系列:

网络安全系列:

嵌入式开发系列:

AI / 机器学习系列:


猜你喜欢

转载自blog.csdn.net/HowieXue/article/details/129541901