using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; namespace Ads.Desktop; public sealed record PortProcess(int Id, string Name, long StartedUtcTicks); public static class LocalPortProcesses { public static void EnsureAvailable(int port) { ValidatePort(port); var probe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, port); try { probe.Server.ExclusiveAddressUse = true; probe.Start(); } catch (System.Net.Sockets.SocketException) { throw new InvalidOperationException($"本地端口 {port} 仍不可用,可能被自动重启的程序占用或受系统限制。"); } finally { probe.Stop(); } } public static IReadOnlyList Inspect(int port) { ValidatePort(port); var result = new List(); foreach (var id in ListenerIds(port)) { try { using var process = Process.GetProcessById(id); result.Add(new PortProcess(id, process.ProcessName, process.StartTime.ToUniversalTime().Ticks)); } catch (ArgumentException) { /* Listener exited during inspection. */ } catch (Win32Exception) { throw new InvalidOperationException($"无法读取端口 {port} 的进程 PID {id},请检查账户权限。"); } } return result; } public static async Task TerminateAsync(int port, IReadOnlyList inspected, CancellationToken cancellation = default) { ValidatePort(port); if (port == 5037) throw new InvalidOperationException("5037 是 ADB 主服务端口,请选择隧道端口,避免中断其他设备。"); var ended = 0; foreach (var owner in inspected) { cancellation.ThrowIfCancellationRequested(); if (owner.Id <= 4 || owner.Id == Environment.ProcessId) throw new InvalidOperationException($"端口由系统或当前工作台进程占用,不能一键结束 PID {owner.Id}。"); // Re-check both port ownership and process creation time immediately // before termination. Never kill by process name or a stale PID alone. if (!ListenerIds(port).Contains(owner.Id)) continue; try { using var process = Process.GetProcessById(owner.Id); if (process.StartTime.ToUniversalTime().Ticks != owner.StartedUtcTicks) throw new InvalidOperationException("进程身份已变化,请重新检查端口后再清理。"); if (process.HasExited) continue; process.Kill(entireProcessTree: false); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); timeout.CancelAfter(TimeSpan.FromSeconds(5)); await process.WaitForExitAsync(timeout.Token); ended++; } catch (ArgumentException) { } catch (Win32Exception) { throw new InvalidOperationException($"无法结束 {owner.Name}(PID {owner.Id}),请检查权限或用管理员身份运行工作台。"); } } await WaitUntilAvailableAsync(port, cancellation); return ended; } public static async Task WaitUntilAvailableAsync(int port, CancellationToken cancellation = default) { for (var attempt = 0; attempt < 50; attempt++) { cancellation.ThrowIfCancellationRequested(); if (ListenerIds(port).Count == 0) try { EnsureAvailable(port); return; } catch (InvalidOperationException) { } await Task.Delay(100, cancellation); } throw new InvalidOperationException($"端口 {port} 仍不可用,或占用程序已自动重启,请重新检查。"); } private static void ValidatePort(int port) { if (port is < 1024 or > 65535) throw new InvalidOperationException("请选择 1024–65535 范围内的本地端口。"); } private static HashSet ListenerIds(int port) { if (OperatingSystem.IsWindows()) { var ids = WindowsListenerIds(port, 2, 24, 8, 20); ids.UnionWith(WindowsListenerIds(port, 23, 56, 20, 52)); return ids; } // macOS provides lsof; Linux can use the same interface when installed. var info = new ProcessStartInfo("lsof") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; foreach (var argument in new[] { "-nP", $"-iTCP:{port}", "-sTCP:LISTEN", "-t" }) info.ArgumentList.Add(argument); try { using var process = Process.Start(info) ?? throw new InvalidOperationException("无法启动 lsof。"); var stdout = process.StandardOutput.ReadToEndAsync(); var stderr = process.StandardError.ReadToEndAsync(); if (!process.WaitForExit(5000)) { process.Kill(); throw new InvalidOperationException("检查端口超时。"); } var output = stdout.GetAwaiter().GetResult(); var error = stderr.GetAwaiter().GetResult(); if (process.ExitCode != 0 && (process.ExitCode != 1 || error.Length > 0)) throw new InvalidOperationException("lsof 无法检查端口:" + error.Trim()); return output.Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(line => int.TryParse(line.Trim(), out var id) ? id : -1).Where(id => id > 0).ToHashSet(); } catch (Win32Exception) { throw new InvalidOperationException("此平台检查端口需要 lsof,请先安装后重试。"); } } private static HashSet WindowsListenerIds(int port, int family, int rowSize, int portOffset, int pidOffset) { var result = new HashSet(); for (var attempt = 0; attempt < 3; attempt++) { var size = 0; var status = GetExtendedTcpTable(IntPtr.Zero, ref size, true, family, 3, 0); if (status == 0 && size == 0) return result; if (status != 122 && status != 0) throw new Win32Exception((int)status); var table = Marshal.AllocHGlobal(size); try { status = GetExtendedTcpTable(table, ref size, true, family, 3, 0); if (status == 122) continue; if (status != 0) throw new Win32Exception((int)status); var count = Marshal.ReadInt32(table); if (count < 0 || size < 4 || count > (size - 4) / rowSize) throw new InvalidOperationException("系统端口表格式无效。"); for (var index = 0; index < count; index++) { var row = IntPtr.Add(table, 4 + index * rowSize); var networkPort = (uint)Marshal.ReadInt32(row, portOffset); var localPort = (int)(((networkPort & 0xff) << 8) | ((networkPort >> 8) & 0xff)); if (localPort == port) result.Add(Marshal.ReadInt32(row, pidOffset)); } return result; } finally { Marshal.FreeHGlobal(table); } } throw new InvalidOperationException("系统端口表正在变化,请重试。"); } [DllImport("iphlpapi.dll", SetLastError = true)] private static extern uint GetExtendedTcpTable(IntPtr table, ref int size, [MarshalAs(UnmanagedType.Bool)] bool ordered, int family, int tableClass, uint reserved); }