Is it possible to enumerate all open connections of the current process using .NET? (similarly to the way the netstat tool does this)
Asked
Active
Viewed 1,942 times
3
-
1are you asking about TCP/UDP Connection? – YOusaFZai Dec 09 '13 at 08:06
-
@SALMAN KHAN, TCP would suffice for my task – user626528 Dec 09 '13 at 08:11
-
http://stackoverflow.com/questions/1819364/how-to-determine-tcp-port-used-by-windows-process-in-c-sharp – YOusaFZai Dec 09 '13 at 08:19
2 Answers
2
You can do this with the IPGlobalProperties
class in .NET. With an instance, you can get any of the three things that netstat
generally shows:
- Active TCP connections, via
GetActiveTcpConnections()
- Active TCP listeners, via
GetActiveTcpListeners()
- Active UDP listeners, via
GetActiveUdpListeners()
Note that there's no such thing as a "UDP connection".
Here's a simple version of netstat, using this 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();
}
}
}

Jonathon Reinhart
- 132,704
- 33
- 254
- 328
0
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
you have to convert this array to IEnum

YOusaFZai
- 698
- 5
- 21
-
1Note that Array already implements `IEnumerable` - no need to convert. – Jonathon Reinhart Dec 09 '13 at 09:05