Search code examples
c#.nettcpudpport

How to get the ports that are in "ESTABLISHED" state in C#


I am new to the .NET framework.

Currently working on a program that checks if the port is ready to use. I have used IPGlobalProperties to get the port info which was specified here

IPGlobalProperties ipGP = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpEndPoints= ipGP.GetActiveTcpListeners();
IPEndPoint[] updEndPoints = ipGP.GetActiveUdpListeners();
// port validation

Since "ESTABLISHED" & "LISTENING" states refer to open ports as per this post

I also need a solution to get the port that is in the "ESTABLISHED" state. Is there a way to get the ports that are in the "ESTABLISHED" state in C#


Solution

  • Not sure what you want to see exactly, but this will show you all the active local established sockets and ports

         var active = result.GetActiveTcpConnections().Where(c => c.State == TcpState.Established);
         active.Select(c => $"{c.LocalEndPoint.Address} {c.LocalEndPoint.Port}")
                .ToList()
                .ForEach(Console.WriteLine);