14

How can I get all the the active TCP connections using .NET Framework (no unmanaged PE import!)?

I'm getting into socket programming and would like to check this. In my research I found solutions by importing an unmanaged DLL file which I am not interested in.

Cœur
  • 37,241
  • 25
  • 195
  • 267
RollRoll
  • 8,133
  • 20
  • 76
  • 135

1 Answers1

33

I'm surprised with the quantity of users telling me that was not possible to do with pure managed code... For future users who is wondering about that, find the details from the answer that worked fine for me:

//Don't forget this:
using System.Net.NetworkInformation;

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());
    }
}

And call ShowActiveTcpConnections() to list it, awesome and beautiful.

Source: IPGlobalProperties.GetActiveTcpConnections Method (MSDN)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RollRoll
  • 8,133
  • 20
  • 76
  • 135
  • is this a costfull stuff, for getting tcp connections. ie. I want to use this on live environment behind a web request, is it ok? – mehmet mecek Oct 30 '15 at 13:14
  • 2
    I know I am late to the party but you could make it even simpler if this is all you are doing, `foreach(var c in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections())` – chewpoclypse Jul 30 '16 at 06:35
  • 1
    Great answer! but is there any way we can get more info? Like the process responsible for the connections? (As shown in the Resources monitor) – Matheus Rocha Jun 16 '18 at 12:09
  • Can anyone tell me if IPGlobalProperties.GetActiveTcpConnections() or GetActiveTcpListeners triggers a port scan that could be blocked by the Windows firewall or a GPO on the Active Directory? – Nat Nov 01 '18 at 14:33
  • @Pierre Use .net core – jjxtra Apr 12 '19 at 00:48
  • @jjxtra Does the methods exist in .Net Core for PCL? Because Mono Framework kind of does its own thing... I'll give it a shot – Pierre Apr 12 '19 at 05:59