Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

tcp

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"
like image 909
Wheelie Avatar asked Nov 30 '09 11:11

Wheelie


People also ask

How do I find TCP port number in Windows?

How to find your port number on Windows. Type “Cmd” in the search box. Open “Command Prompt”. Enter the netstat -a command to see your port numbers.


2 Answers

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.

like image 178
Rubens Farias Avatar answered Nov 14 '22 22:11

Rubens Farias


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.

like image 42
Konamiman Avatar answered Nov 14 '22 21:11

Konamiman