C#中获取网络连接信息有没有netstat命令的替代方案?
C# 不依赖netstat获取系统活跃连接的实现方案
你可以直接使用.NET 类库内置的 System.Net.NetworkInformation 命名空间下的API实现需求,不需要调用外部cmd进程执行netstat命令,就能直接获取结构化的连接数据,包含你需要的协议、本地地址、外部地址、连接状态、进程ID所有字段。
代码实现示例
.NET Core 3.0+ / .NET 5+ 版本
该版本框架原生封装了进程ID字段的获取,无需额外调用系统API:
using System; using System.Net.NetworkInformation; class ConnectionCollector { public static void GetAllActiveConnections() { IPGlobalProperties networkInfo = IPGlobalProperties.GetIPGlobalProperties(); // 采集TCP连接信息 TcpConnectionInformation[] allTcpConnections = networkInfo.GetActiveTcpConnections(); Console.WriteLine("=== TCP 活跃连接 ==="); Console.WriteLine("协议\t本地地址\t外部地址\t连接状态\t进程ID"); foreach (var tcpConn in allTcpConnections) { Console.WriteLine($"TCP\t{tcpConn.LocalEndPoint}\t{tcpConn.RemoteEndPoint}\t{tcpConn.State}\t{tcpConn.ProcessId}"); } // 采集UDP监听信息(UDP为无连接协议,仅存在监听端点,无外部地址和连接状态) UdpListenerInformation[] allUdpListeners = networkInfo.GetActiveUdpListeners(); Console.WriteLine("\n=== UDP 监听端点 ==="); Console.WriteLine("协议\t本地地址\t进程ID"); foreach (var udpListener in allUdpListeners) { Console.WriteLine($"UDP\t{udpListener.LocalEndPoint}\t{udpListener.ProcessId}"); } } }
.NET Framework 版本
.NET Framework 原生的 TcpConnectionInformation 未暴露进程ID属性,你可以通过调用Windows系统iphlpapi.dll内置的GetExtendedTcpTable、GetExtendedUdpTable API实现相同需求,传入TCP_TABLE_OWNER_PID_ALL参数即可拿到带进程ID的完整连接表。
方案优势
- 无外部进程依赖,避免了进程启动开销、文本输出解析的兼容性问题,不会因为系统语言、netstat版本差异导致解析错误
- 直接获取结构化数据,开发和维护成本更低
- 权限要求和netstat命令完全一致,普通用户权限即可采集绝大多数连接信息
内容的提问来源于stack exchange,提问作者Akash Kumar
相关产品推荐
相关产品推荐

