using System.ComponentModel; using System.Diagnostics; using System.Net; using System.Runtime.InteropServices; using System.Text; namespace XFEToolBox.QuickTools; public sealed record ProcessIdentity(int Pid, string Name, string Path, long StartedUtcTicks, string WindowTitle) { public string Description => $"{Name} · PID {Pid}\n{Path}\n{(StartedUtcTicks > 0 ? new DateTime(StartedUtcTicks, DateTimeKind.Utc).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") : "无权读取启动时间")}\n{WindowTitle}"; } public sealed record PortEntry(string Protocol, string LocalAddress, int Port, string RemoteAddress, string State, ProcessIdentity Process) { public string Display => $"{Protocol,-5} {LocalAddress}:{Port} {State} {Process.Name} / {Process.Pid}"; public string Details => Display + "\n远端:" + RemoteAddress + "\n" + Process.Description; } public static class PortInspector { public static IReadOnlyList Query(int? port = null) { if (port is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(port), "端口范围 1–65535。"); var rows = new List(); var processes = new Dictionary(); foreach (bool tcp in new[] { true, false }) foreach (int family in new[] { 2, 23 }) { uint size = 0; uint rc = tcp ? GetExtendedTcpTable(0, ref size, false, family, 5, 0) : GetExtendedUdpTable(0, ref size, false, family, 1, 0); if (rc != 122 && rc != 0) throw new Win32Exception((int)rc); if (size == 0) continue; nint buffer = 0; try { for (int retry = 0; retry < 4; retry++) { if (buffer != 0) Marshal.FreeHGlobal(buffer); if (size > 64 * 1024 * 1024) throw new InvalidOperationException("系统端口表过大。"); buffer = Marshal.AllocHGlobal((int)size); rc = tcp ? GetExtendedTcpTable(buffer, ref size, false, family, 5, 0) : GetExtendedUdpTable(buffer, ref size, false, family, 1, 0); if (rc != 122) break; } if (rc != 0) throw new Win32Exception((int)rc); int count = Marshal.ReadInt32(buffer), rowSize = tcp ? (family == 2 ? 24 : 56) : (family == 2 ? 12 : 28); if (count < 0 || 4L + (long)count * rowSize > size) throw new InvalidOperationException("系统端口表大小无效。"); for (int i = 0; i < count; i++) { nint row = buffer + 4 + i * rowSize; int localPortOffset = family == 2 ? (tcp ? 8 : 4) : 20; int localPort = ReadPort(row + localPortOffset); if (port.HasValue && localPort != port.Value) continue; int pid = Marshal.ReadInt32(row + rowSize - 4); if (!processes.TryGetValue(pid, out var process)) processes[pid] = process = ReadProcess(pid); string local = family == 2 ? ReadAddress(row + (tcp ? 4 : 0), 4, 0) : ReadAddress(row, 16, (uint)Marshal.ReadInt32(row + 16)); string remote = tcp ? (family == 2 ? ReadAddress(row + 12, 4, 0) + ":" + ReadPort(row + 16) : "[" + ReadAddress(row + 24, 16, (uint)Marshal.ReadInt32(row + 40)) + "]:" + ReadPort(row + 44)) : "—"; int state = tcp ? Marshal.ReadInt32(row + (family == 2 ? 0 : 48)) : 0; rows.Add(new(tcp ? (family == 2 ? "TCP4" : "TCP6") : (family == 2 ? "UDP4" : "UDP6"), family == 23 ? "[" + local + "]" : local, localPort, remote, tcp ? TcpState(state) : "绑定", process)); } } finally { if (buffer != 0) Marshal.FreeHGlobal(buffer); } } return rows.OrderBy(r => r.Port).ThenBy(r => r.Protocol).ThenBy(r => r.Process.Pid).ToArray(); } private static string TcpState(int state) => state switch { 1 => "关闭", 2 => "监听", 3 => "SYN_SENT", 4 => "SYN_RCVD", 5 => "已连接", 6 => "FIN_WAIT1", 7 => "FIN_WAIT2", 8 => "CLOSE_WAIT", 9 => "CLOSING", 10 => "LAST_ACK", 11 => "TIME_WAIT", 12 => "DELETE_TCB", _ => "未知" }; private static int ReadPort(nint ptr) => (Marshal.ReadByte(ptr) << 8) | Marshal.ReadByte(ptr + 1); private static string ReadAddress(nint p, int bytes, long scope) { byte[] address = new byte[bytes]; Marshal.Copy(p, address, 0, bytes); return (bytes == 16 ? new IPAddress(address, scope) : new IPAddress(address)).ToString(); } public static ProcessIdentity ReadProcess(int pid) { string name = pid == 0 ? "系统空闲" : "无法读取", path = "访问受限或进程已退出", title = ""; long started = 0; try { using var p = Process.GetProcessById(pid); name = p.ProcessName; title = p.MainWindowTitle; started = p.StartTime.ToUniversalTime().Ticks; } catch { } nint handle = OpenProcess(0x1000, false, pid); if (handle != 0) try { var value = new StringBuilder(32768); uint size = (uint)value.Capacity; if (QueryFullProcessImageName(handle, 0, value, ref size)) path = value.ToString(); } finally { CloseHandle(handle); } return new(pid, name, path, started, title); } public static void Terminate(ProcessIdentity expected) { if (expected.Pid <= 4 || expected.Pid == Environment.ProcessId || expected.StartedUtcTicks == 0 || new[] { "csrss", "wininit", "winlogon", "services", "lsass", "smss", "System", "Registry", "Memory Compression" }.Contains(expected.Name, StringComparer.OrdinalIgnoreCase)) throw new InvalidOperationException("拒绝结束系统关键进程、本工具或身份未经确认的进程。"); nint handle = OpenProcess(0x101001, false, expected.Pid); if (handle == 0) throw new Win32Exception(Marshal.GetLastWin32Error(), "无法获取进程权限;进程可能已退出或需要管理员权限。"); try { if (!GetProcessTimes(handle, out long creation, out _, out _, out _) || DateTime.FromFileTimeUtc(creation).Ticks != expected.StartedUtcTicks) throw new InvalidOperationException("进程身份已变化,请重新查询。"); var path = new StringBuilder(32768); uint size = (uint)path.Capacity; if (!QueryFullProcessImageName(handle, 0, path, ref size) || !path.ToString().Equals(expected.Path, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("进程路径无法确认,请重新查询。"); if (!IsProcessCritical(handle, out bool critical) || critical) throw new InvalidOperationException("无法确认进程安全性,已拒绝结束。"); if (!TerminateProcess(handle, 1)) throw new Win32Exception(Marshal.GetLastWin32Error()); if (WaitForSingleObject(handle, 5000) != 0) throw new InvalidOperationException("已发送结束请求,但进程尚未完成退出;请稍后刷新。端口表可能短暂保留旧记录。"); } finally { CloseHandle(handle); } } [DllImport("iphlpapi.dll")] private static extern uint GetExtendedTcpTable(nint table, ref uint size, bool order, int family, int kind, uint reserved); [DllImport("iphlpapi.dll")] private static extern uint GetExtendedUdpTable(nint table, ref uint size, bool order, int family, int kind, uint reserved); [DllImport("kernel32.dll", SetLastError = true)] private static extern nint OpenProcess(uint access, bool inherit, int pid); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern bool QueryFullProcessImageName(nint process, uint flags, StringBuilder path, ref uint size); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetProcessTimes(nint process, out long created, out long exited, out long kernel, out long user); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool IsProcessCritical(nint process, out bool critical); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool TerminateProcess(nint process, uint code); [DllImport("kernel32.dll", SetLastError = true)] private static extern uint WaitForSingleObject(nint handle, uint milliseconds); [DllImport("kernel32.dll")] private static extern bool CloseHandle(nint handle); }