If you are doing low level TCP networking in .Net and in particular are using a TcpListener on a client to listen for callbacks form a server, you need to select a port on which to listen. Typically, in this scenario, you don’t want to have to specify a port in the .config file. You just want to pick any open port (well actually, any open port, in the IANA private port range).

After looking around the net, I found some almost correct but not quite code for this, so I though I should post my improved version here.

The below function will return the first open port in the IANA port range that is not currently being used on the local machine.

Be careful however. Just because the port is not used at the point the code is called, doesn’t mean it won’t be in use when you go to open your listener. Just incase some other process grabbed the port in the interim, you should always open your listener in a try catch block and if the call fails because the port is in use, grab another available port and try again.

private static int SelectAvailablePort()
{
    const int START_OF_IANA_PRIVATE_PORT_RANGE = 49152;
    var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    var tcpListeners = ipGlobalProperties.GetActiveTcpListeners();
    var tcpConnections = ipGlobalProperties.GetActiveTcpConnections();
 
    var allInUseTcpPorts = tcpListeners.Select(tcpl => tcpl.Port)
        .Union(tcpConnections.Select(tcpi => tcpi.LocalEndPoint.Port));
 
    var orderedListOfPrivateInUseTcpPorts = allInUseTcpPorts
        .Where(p => p >= START_OF_IANA_PRIVATE_PORT_RANGE)
        .OrderBy(p => p);
 
    var candidatePort = START_OF_IANA_PRIVATE_PORT_RANGE;
    foreach (var usedPort in orderedListOfPrivateInUseTcpPorts)
    {
        if (usedPort != candidatePort) break;
        candidatePort++;
    }
    return candidatePort;
}

Disclaimer: I am by no means an network programming guru. If you find issues with this snippet or have a better one, please let me know.