3

Is it possible to enumerate all open connections of the current process using .NET? (similarly to the way the netstat tool does this)

user626528
  • 13,999
  • 30
  • 78
  • 146

2 Answers2

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:

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