枚举所有打开的连接

是否可以使用.NET枚举当前进程的所有打开连接? (类似于netstat工具执行此操作的方式)

IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] connections = properties.GetActiveTcpConnections(); 

你必须将此数组转换为IEnum

您可以使用.NET中的IPGlobalProperties类来完成此操作。 使用实例,您可以获得netstat通常显示的三个内容中的任何一个:

  • 活动TCP连接,通过GetActiveTcpConnections()
  • 活动TCP侦听器,通过GetActiveTcpListeners()
  • 活动UDP侦听器,通过GetActiveUdpListeners()

请注意,没有“UDP连接”这样的东西。

这是使用此API的netstat的简单版本:

 using System; using System.Net.NetworkInformation; namespace NetStatNet { class Program { static void Main(string[] args) { var props = IPGlobalProperties.GetIPGlobalProperties(); Console.WriteLine(" Proto Local Address Foreign Address State"); foreach (var conn in props.GetActiveTcpConnections()) Console.WriteLine(" TCP {0,-23}{1,-23}{2}", conn.LocalEndPoint, conn.RemoteEndPoint, conn.State); foreach (var listener in props.GetActiveTcpListeners()) Console.WriteLine(" TCP {0,-23}{1,-23}{2}", listener, "", "Listening"); foreach (var listener in props.GetActiveUdpListeners()) Console.WriteLine(" UDP {0,-23}{1,-23}{2}", listener, "", "Listening"); Console.Read(); } } }