7

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 following CMD line:

netstat -ano |find /i "listening"
Wheelie
  • 3,866
  • 2
  • 33
  • 39

2 Answers2

15

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.

Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
  • 6
    And to get also the PID? – Revious Mar 06 '15 at 11:44
  • 1
    Link to "Build your own netstat" is broken. [@Konamiman's comment](https://stackoverflow.com/a/1819388/2410234) has a working link: https://timvw.be/2007/09/09/build-your-own-netstatexe-with-c/ – EddPorter Jul 02 '18 at 14:37
  • @EddPorter Update: https://web.archive.org/web/20150520071202/http://www.timvw.be/2007/09/09/build-your-own-netstatexe-with-c/ – user3625699 Feb 10 '21 at 00:49
  • 1
    Site still online, just more a dot: https://timvw.be/2007/09/09/build-your-own-netstat.exe-with-c But it works with WinAPI – Mr. Squirrel.Downy Jun 09 '22 at 10:39
3

See here for an equivalent of netstat in C#: http://towardsnext.wordpess.com/2009/02/09/netstat-in-c/

Update: Link is broken, but here's an equivalent: http://www.timvw.be/2007/09/09/build-your-own-netstatexe-with-c

Update: The original page has been archived at the Wayback Machine.

InteXX
  • 6,135
  • 6
  • 43
  • 80
Konamiman
  • 49,681
  • 17
  • 108
  • 138