使用Python编程检测计算机是否连接Wifi或以太网的方法
Python检测网络连接类型的实现方案
以下提供两类可直接落地的实现方案,覆盖Windows、Linux、macOS三大主流桌面系统。
方案1:跨平台通用方案(依赖第三方库,适配绝大多数场景)
依赖netifaces库实现跨平台识别,无需针对不同系统写适配逻辑。
步骤1:安装依赖
pip install netifaces
步骤2:实现代码
import netifaces def get_network_connection_type(): # 枚举所有网络接口 interfaces = netifaces.interfaces() active_types = [] for iface in interfaces: # 跳过回环接口 if iface.startswith("lo") or iface == "loopback0": continue # 过滤无有效IPv4地址的未激活接口 try: addr_info = netifaces.ifaddresses(iface) if netifaces.AF_INET not in addr_info: continue except ValueError: continue # 根据接口名称特征判断连接类型 if any(key in iface.lower() for key in ["wlan", "wifi", "wi-fi"]): active_types.append("WiFi") elif any(key in iface.lower() for key in ["eth", "ethernet", "en"]): # 排除macOS下同为en前缀的WiFi接口 if not any(key in iface.lower() for key in ["wlan", "wifi"]): active_types.append("以太网") # 去重后返回结果 return list(set(active_types)) # 调用示例 if __name__ == "__main__": result = get_network_connection_type() if result: print(f"当前激活的连接类型:{', '.join(result)}") else: print("未检测到有效网络连接")
方案2:分系统原生实现(准确率更高,无第三方依赖)
针对不同系统调用原生接口判断,避免特殊命名的接口识别错误。
Windows系统实现
调用系统wmic命令获取适配器信息:
import subprocess import re def get_windows_conn_type(): res = subprocess.check_output( "wmic nic where NetEnabled=true get Name,NetConnectionID", shell=True ).decode("gbk", errors="ignore") active_types = [] for line in res.splitlines(): line = line.strip() if not line or "Name" in line: continue if re.search(r"Wi-Fi|无线|WLAN", line, re.I): active_types.append("WiFi") elif re.search(r"以太网|Ethernet|千兆以太网", line, re.I): active_types.append("以太网") return list(set(active_types))
Linux系统实现
读取/sys/class/net目录下的系统文件判断:
import os def get_linux_conn_type(): active_types = [] net_root = "/sys/class/net/" for iface in os.listdir(net_root): if iface.startswith("lo"): continue # 过滤未接入网络的接口 carrier_path = os.path.join(net_root, iface, "carrier") if not os.path.exists(carrier_path): continue with open(carrier_path, "r") as f: if f.read().strip() != "1": continue # 无线接口存在wireless子目录,以太网无该目录 wireless_flag = os.path.join(net_root, iface, "wireless") if os.path.exists(wireless_flag): active_types.append("WiFi") else: active_types.append("以太网") return list(set(active_types))
macOS系统实现
调用系统networksetup命令判断:
import subprocess def get_macos_conn_type(): res = subprocess.check_output( ["networksetup", "-listallhardwareports"], text=True ) active_types = [] current_type = None for line in res.splitlines(): line = line.strip() if line.startswith("Hardware Port:"): port_name = line.split(":", 1)[1].strip() if "Wi-Fi" in port_name: current_type = "WiFi" elif "Ethernet" in port_name or "Thunderbolt Ethernet" in port_name: current_type = "以太网" else: current_type = None elif line.startswith("Device:") and current_type: dev_name = line.split(":", 1)[1].strip() # 验证接口是否已分配IP(处于激活状态) try: ip_res = subprocess.check_output( ["ipconfig", "getifaddr", dev_name], text=True, stderr=subprocess.DEVNULL ) if ip_res.strip(): active_types.append(current_type) except subprocess.CalledProcessError: pass return list(set(active_types))
可结合platform.system()判断当前运行的系统,自动调用对应逻辑即可。
内容的提问来源于stack exchange,提问作者Ahsan
相关产品推荐
相关产品推荐

