How to determine tcp port used by Windows process in C#

后端 未结 2 1365
耶瑟儿~
耶瑟儿~ 2020-12-03 06:10

Is there a managed class/method that would provide the TCP port number(s) used by a particular Windows processes?

I\'m really looking for a .NET equivalent of the fo

2条回答
  •  萌比男神i
    2020-12-03 06:40

    Except for PID, take a look this:

    IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
    
    IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
    TcpConnectionInformation[] tcpConnections = 
        ipProperties.GetActiveTcpConnections();
    
    foreach (TcpConnectionInformation info in tcpConnections)
    {
        Console.WriteLine("Local: {0}:{1}\nRemote: {2}:{3}\nState: {4}\n", 
            info.LocalEndPoint.Address, info.LocalEndPoint.Port,
            info.RemoteEndPoint.Address, info.RemoteEndPoint.Port,
            info.State.ToString());
    }
    Console.ReadLine();
    

    Source: Netstat in C#

    A bit more research bring this: Build your own netstat.exe with c#. This uses P/Invoke to call GetExtendedTcpTable and using same structure as netstat.

提交回复
热议问题