0

I am writing a C# program which tells the Active Connections (Protocal, Local Address , Foreign Address , State , Process Id ) . To do this I am running cmd.exe as a process and passing netstat -ano as an argument.

System.Diagnostics.Process.Start("cmd.exe","netstat -ano");

This returns Active connections . But I don't want to use this netstat command .
Is there any alternative for netstat.exe in C# ?
Any library or something else so that I can get the same output ?

Akash Kumar
  • 307
  • 1
  • 4
  • 9

2 Answers2

3

You do not need to run nmap or netstat, you can get all the info much easier when you take a look at the System.Net.NetworkInformation namespace. There you can find charming things like GetActiveTcpListeners() or GetActiveTcpConnections() and much more.

public static void ShowActiveTcpConnections()
{
           Console.WriteLine("Active TCP Connections");
           IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
           TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
           foreach (TcpConnectionInformation c in connections)
           {
               Console.WriteLine("{0} <==> {1}",
                   c.LocalEndPoint.ToString(),
                   c.RemoteEndPoint.ToString());
           }
}

Details are here in the docs:

https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.ipglobalproperties.getactivetcpconnections?view=net-5.0

Rob
  • 11,492
  • 14
  • 59
  • 94
  • Process id is not being shown there. Is there any way to get the process id also ? By the way thanks for the help. – Akash Kumar Sep 02 '21 at 08:38
1

I was looking for an netstat alternative as you and I found nmap.

To scan I usually run:

nmap -sP 192.168.1.*
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30