修复WiFi ADB随机端口扫描

This commit is contained in:
Your Name committed 2026-06-03 17:52:02 +08:00
1 parent daf0c49288
commit bcc4d1151f
6 files changed
+137 -54

No files matched your search

+2 -9
View File
@@ -120,15 +120,8 @@ def try_reconnect_last_wifi(
_safe_after(root, notify_scan_start, fallback=notify_scan_start)
try:
# 如果上次记的端口非 5555,扫描时把它一起带上(覆盖 Android 11+ 随机端口)
last_port_int = 5555
if ":" in target:
try:
last_port_int = int(target.rsplit(":", 1)[1])
except ValueError:
pass
scan_ports = [5555] if last_port_int == 5555 else [5555, last_port_int]
devs = discover_adb_devices(adb_exe, ports=scan_ports)
# 自动模式会先验证上次目标,再对在线候选主机补扫完整端口段。
devs = discover_adb_devices(adb_exe)
except Exception as e:
def render_scan_err():
on_line(f"[启动] 自动扫描失败: {e}")
+1 -1
View File
@@ -74,7 +74,7 @@ def open_scan_dialog(
).grid(row=2, column=0, columnspan=4, sticky=W, pady=(4, 0))
ttk.Label(
top_frame,
text="端口留空=快速自动;手动示例: 5555 | 5555,5556 | 37000-44000 (Android 无线调试随机端口)",
text="端口留空=自动完整扫候选主机 1-65535;手动示例: 5555 | 44219 | 37000-65535",
font=("Arial", 8),
foreground="gray",
).grid(row=3, column=0, columnspan=4, sticky=W, pady=(2, 0))
+78 -24
View File
@@ -20,7 +20,9 @@ from typing import Callable, Iterable, Optional
DEFAULT_ADB_PORT = 5555
HI_PORT_MIN = 37000
HI_PORT_MAX = 44000
HI_PORT_MAX = 65535
FULL_PORT_MIN = 1
FULL_PORT_MAX = 65535
# 高端口补扫先做一轮均匀采样,命中率够高时可以明显缩短等待。
HI_PORT_SAMPLE_COUNT = 192
FAST_PROBE_TIMEOUT = 0.12
@@ -30,7 +32,8 @@ DEFAULT_SCAN_TIMEOUT = 0.12
MAX_QUICK_HOSTS = 24
# 默认扫描端口集合:5555 是传统 adb tcpip 端口;Android 11+ 无线调试
# 随机端口走 discover_adb_devices 的 mDNS / ARP / 上次目标快速路径补扫。
# 随机端口走 discover_adb_devices 的 mDNS / ARP / 上次目标快速路径补扫;
# 覆盖优先:仅对少量在线候选主机补扫完整 1-65535 端口段。
DEFAULT_ADB_PORTS: tuple[int, ...] = (DEFAULT_ADB_PORT,)
@@ -427,6 +430,41 @@ def _build_hi_port_candidates(last_port_hint: Optional[int] = None) -> list[int]
return out
def _build_full_hi_port_range(last_port_hint: Optional[int] = None) -> list[int]:
"""完整无线调试高端口段,仅用于少量在线候选主机的兼容补扫。"""
out: list[int] = []
seen: set[int] = set()
if (
isinstance(last_port_hint, int)
and HI_PORT_MIN <= last_port_hint <= HI_PORT_MAX
):
out.append(last_port_hint)
seen.add(last_port_hint)
for p in range(HI_PORT_MIN, HI_PORT_MAX + 1):
if p in seen:
continue
out.append(p)
return out
def _build_full_port_range(last_port_hint: Optional[int] = None) -> list[int]:
"""完整端口段,仅用于少量在线候选主机,优先保证不漏随机端口。"""
out: list[int] = []
seen: set[int] = set()
preferred = [last_port_hint, DEFAULT_ADB_PORT]
for maybe_port in preferred:
if not isinstance(maybe_port, int):
continue
if FULL_PORT_MIN <= maybe_port <= FULL_PORT_MAX and maybe_port not in seen:
seen.add(maybe_port)
out.append(maybe_port)
for p in range(FULL_PORT_MIN, FULL_PORT_MAX + 1):
if p in seen:
continue
out.append(p)
return out
def _append_unique_ip(out: list[str], seen: set[str], ip: str, subnet_specs: list[str]) -> None:
try:
ipaddress.IPv4Address(ip)
@@ -541,28 +579,45 @@ def scan_open_ports(
if not ip_list or not port_list:
return []
targets = [(ip, p) for ip in ip_list for p in port_list]
total = len(targets)
total = len(ip_list) * len(port_list)
open_targets: list[tuple[str, int]] = []
done = 0
def iter_targets():
for ip in ip_list:
for p in port_list:
yield ip, p
batch_size = max(int(max_workers) * 8, 1)
target_iter = iter_targets()
with ThreadPoolExecutor(max_workers=max_workers) as ex:
future_map = {
ex.submit(probe_adb_port, ip, p, timeout): (ip, p)
for ip, p in targets
}
for fut in as_completed(future_map):
done += 1
if on_progress:
try:
on_progress(done, total)
except Exception:
pass
while True:
batch: list[tuple[str, int]] = []
try:
if fut.result():
open_targets.append(future_map[fut])
except Exception:
continue
for _ in range(batch_size):
batch.append(next(target_iter))
except StopIteration:
pass
if not batch:
break
future_map = {
ex.submit(probe_adb_port, ip, p, timeout): (ip, p)
for ip, p in batch
}
for fut in as_completed(future_map):
done += 1
if on_progress:
try:
on_progress(done, total)
except Exception:
pass
try:
if fut.result():
open_targets.append(future_map[fut])
except Exception:
continue
# 按 (ip 数值序, port 升序) 排序,结果稳定
try:
@@ -803,6 +858,7 @@ def discover_adb_devices(
pass
quick_open_targets: list[tuple[str, int]] = []
quick_hosts: list[str] = []
if auto_ports_mode:
quick_hosts = _build_quick_host_candidates(
subnet_specs,
@@ -810,20 +866,18 @@ def discover_adb_devices(
mdns_targets=mdns_targets,
max_hosts=MAX_QUICK_HOSTS,
)
quick_ports = _build_hi_port_candidates(last_port_hint)
if last_port_hint and last_port_hint not in quick_ports:
quick_ports.insert(0, last_port_hint)
quick_ports = _build_full_port_range(last_port_hint)
if quick_hosts and quick_ports:
if on_phase:
try:
on_phase(f"快速补扫 {len(quick_hosts)} 台在线候选 × {len(quick_ports)} 个无线调试高端口")
on_phase(f"完整补扫 {len(quick_hosts)} 台在线候选 × {len(quick_ports)} 个端口")
except Exception:
pass
quick_open_targets = scan_open_ports(
quick_hosts,
ports=quick_ports,
timeout=min(max(probe_timeout, 0.01), 0.025),
max_workers=256,
max_workers=512,
)
# 3) 端口扫描(支持多子网补扫)
+1 -8
View File
@@ -778,14 +778,7 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
}
)
try:
last_port = 5555
if ":" in target:
try:
last_port = int(target.rsplit(":", 1)[1])
except ValueError:
pass
scan_ports = [5555] if last_port == 5555 else [5555, last_port]
devs = discover_adb_devices(adb, ports=scan_ports)
devs = discover_adb_devices(adb)
except Exception as e:
return handler._send_json({"ok": False, "error": f"自动扫描失败: {e}"}, status=500)
best = pick_best_match(devs, last)
+29
View File
@@ -246,6 +246,35 @@ def test_wifi_auto_reconnect_without_adb_returns_422(monkeypatch):
assert obj.get("error") == "adb not found"
def test_wifi_auto_reconnect_uses_auto_full_port_scan(monkeypatch):
captured = {}
monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb")
monkeypatch.setattr(routes, "list_adb_devices", lambda adb: []) # noqa: ARG001
import gui.gui_core_pkg as core_pkg
import gui.gui_core_pkg.wifi_adb_scan as scan_mod
monkeypatch.setattr(
core_pkg,
"get_last_wifi_target",
lambda: {"target": "192.168.10.105:39601", "model": "PEPM00"},
)
monkeypatch.setattr(scan_mod, "verify_adb_target", lambda adb, target: ("failed", "refused")) # noqa: ARG005
def fake_discover(adb, **kwargs): # noqa: ARG001
captured.update(kwargs)
return []
monkeypatch.setattr(core_pkg, "discover_adb_devices", fake_discover)
status, obj = _post("/api/wifi/auto-reconnect", {}, monkeypatch)
assert status == 200
assert obj.get("ok") is True
assert "ports" not in captured
def test_wifi_scan_includes_tried_subnets(monkeypatch):
monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb")
monkeypatch.setattr(routes, "list_adb_devices", lambda adb: []) # noqa: ARG001
+26 -12
View File
@@ -233,10 +233,10 @@ class TestParsePortSpec:
assert result == [5555]
def test_android_wireless_debug_range_allowed(self):
result = scan.parse_port_spec("37000-44000")
result = scan.parse_port_spec("37000-65535")
assert result[0] == 37000
assert result[-1] == 44000
assert len(result) == 7001
assert result[-1] == 65535
assert len(result) == 28536
# ============================================================
@@ -478,17 +478,19 @@ class TestDiscoverAdbDevices:
assert captured_ports
assert captured_ports[0][0] == 37697
assert 5555 not in captured_ports[0]
assert captured_ports[0][1] == 5555
assert 44219 in captured_ports[0]
assert len(captured_ports[0]) == 65535
assert captured_ports[1] == [5555]
def test_auto_mode_quick_high_port_scan_before_base_5555(self):
def test_auto_mode_full_port_scan_before_base_5555(self):
calls = []
def fake_scan_ports(ips, **kwargs):
ports = list(kwargs.get("ports") or [])
calls.append((list(ips), len(ports)))
if ports and ports[0] >= scan.HI_PORT_MIN:
return [("192.168.10.55", 40123)]
calls.append((list(ips), ports))
if 44219 in ports:
return [("192.168.10.55", 44219)]
return []
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/24"]), \
@@ -501,8 +503,11 @@ class TestDiscoverAdbDevices:
devs = scan.discover_adb_devices("/adb")
assert len(devs) == 1
assert calls[0] == (["192.168.10.55"], scan.HI_PORT_SAMPLE_COUNT)
assert calls[1][1] == 1
assert calls[0][0] == ["192.168.10.55"]
assert calls[0][1][0] == scan.DEFAULT_ADB_PORT
assert 44219 in calls[0][1]
assert len(calls[0][1]) == 65535
assert calls[1][1] == [5555]
def test_hi_port_fallback_still_runs_when_last_port_hint_added(self):
calls = []
@@ -510,8 +515,8 @@ class TestDiscoverAdbDevices:
def fake_scan_ports(ips, **kwargs):
ports = list(kwargs.get("ports") or [])
calls.append((list(ips), ports))
if ports and ports[0] >= scan.HI_PORT_MIN:
return [("192.168.10.55", 40123)]
if 44219 in ports:
return [("192.168.10.55", 44219)]
return []
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/24"]), \
@@ -526,4 +531,13 @@ class TestDiscoverAdbDevices:
assert len(devs) == 1
assert calls[0][0] == ["192.168.10.2", "192.168.10.55"]
assert calls[0][1][0] == 37697
assert 44219 in calls[0][1]
assert len(calls[0][1]) == 65535
assert calls[1][1] == [5555]
def test_full_port_scan_covers_44219(self):
ports = scan._build_full_port_range()
assert len(ports) == 65535
assert ports[0] == scan.DEFAULT_ADB_PORT
assert 44219 in ports