From 4c0572f73c29958b570e354b222b2a478eadcbd6 Mon Sep 17 00:00:00 2001 From: butubb <1422726308@qq.com> Date: Wed, 9 Sep 2026 14:16:13 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E8=AE=BE=E5=A4=87=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E5=8F=91=E7=8E=B0=E6=9C=AC=E6=9C=BAIP=E6=9E=9A=E4=B8=BE?= =?UTF-8?q?=E2=80=94=E2=80=94git-bash=20hostname=20-I=20=E6=8A=A5=E9=94=99?= =?UTF-8?q?=E7=82=B8=E7=BA=BF=E7=A8=8B=EF=BC=8C=E6=94=B9=20bytes=20?= =?UTF-8?q?=E6=8E=A5=E6=94=B6=20+=20getaddrinfo=20=E5=85=9C=E5=BA=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows 上 git-bash 的 coreutils hostname 不支持 -I,会把 GBK 报错写进 stderr;text=True 在 subprocess 后台读线程里 utf-8 严格解码会直接炸线程 (主线程 try/except 接不住异步线程异常)。抽 _local_ips():优先 hostname -I 且用 bytes 接收 errors=ignore 解码,不支持/失败时 getaddrinfo 枚举兜底。 扫描网段展开时剔除本机自身 IP,避免探测到自己 5555。 --- core/device_discovery.py | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/core/device_discovery.py b/core/device_discovery.py index 60cde19..29ed1c3 100644 --- a/core/device_discovery.py +++ b/core/device_discovery.py @@ -114,17 +114,39 @@ def save_settings(enabled=None, subnets=None, interval=None, port=None): # ================== 网段展开与端口探测 ================== +def _local_ips(): + """本机自身 IP 集合(尽力而为):扫描时排除,避免探测到自己的 5555。 + + 优先 `hostname -I`(Linux/macOS 支持,一行空格分隔多 IP);不支持/失败的 + 平台退回 socket.getaddrinfo 枚举。关键:外部命令必须用 bytes 收——Windows + 上 git-bash 的 coreutils hostname 不支持 -I,会把 GBK 报错写进 stderr, + text=True 在 subprocess 后台读线程里 utf-8 严格解码会直接炸线程(主线程 + try/except 接不住异步线程异常)。 + """ + import subprocess + ips = set() + try: + r = subprocess.run(["hostname", "-I"], capture_output=True, timeout=3) + if r.returncode == 0: + ips.update(p for p in + r.stdout.decode("utf-8", errors="ignore").split() if p) + except Exception: + pass + if not ips: # 兜底:主机名解析出的接口 IPv4 + try: + for info in socket.getaddrinfo(socket.gethostname(), None): + ip = info[4][0] + if ":" not in ip: + ips.add(ip) + except Exception: + pass + return ips + + def _expand_subnets(subnets, max_hosts=_MAX_HOSTS_PER_SUBNET): """CIDR 列表 → IP 列表。排除 220 自身(USB_ADB_HOST)与本机 IP; 非法网段跳过记日志;单网段超过 max_hosts 截断并告警。""" - self_ips = {USB_ADB_HOST} - try: # 本机自身 IP(接口枚举,尽力而为;无 hostname -I 的平台跳过) - import subprocess - out = subprocess.run(["hostname", "-I"], capture_output=True, text=True, - timeout=3).stdout or "" - self_ips.update(p for p in out.split() if p) - except Exception: - pass + self_ips = {USB_ADB_HOST} | _local_ips() ips = [] for cidr in subnets: try: