Is it possible to enumerate all open connections of the current process using .NET? (similarly to the way the netstat tool does this)
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:
GetActiveTcpConnections()
GetActiveTcpListeners()
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();
}
}
}
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
you have to convert this array to IEnum
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.