2013-12-09 62 views
3

是否有可能使用.NET枚举当前进程的所有打开连接? (同样的方式使用netstat工具做到这一点)枚举所有打开的连接

+1

你要问关于TCP/UDP连接? – YOusaFZai

+0

@SALMAN KHAN,TCP就足够我的任务 – user626528

+0

http://stackoverflow.com/questions/1819364/how-to-determine-tcp-port-used-by-windows-process-in-c-sharp – YOusaFZai

回答

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

则必须将此数组转换为IEnum

+0

请注意,数组已经实现了'IEnumerable' - 不需要转换。 –

+0

thanx纠正我... – YOusaFZai

0

您可以在.NET中IPGlobalProperties类做到这一点。有了一个实例,您可以得到任何的三件事netstat通常显示:

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

这里的netstat的简单版本,使用这个API:

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(); 
     } 
    } 
}