If you ever find yourself needing to write a network server application, an issue you will quickly face is finding an available port.

There are two ways to go about this:

  1. Using a TCPListener
  2. Using a Socket

Using A TCP Listener

The first technique is to create a TCPListener, binding it to the Loopback address on Port 0.

This will request an available port from the operating system.

int TcpListenerGetFreePort()
{
    using var listener = new TcpListener(IPAddress.Loopback, 0);
    listener.Start();
    return ((IPEndPoint)listener.LocalEndpoint).Port;
}

Using A Socket

The other technique is to use a Socket directly, like so:

int SocketGetFreePort()
{
    using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
    {
        s.Bind(new IPEndPoint(IPAddress.Loopback, 0));
        return ((IPEndPoint)s.LocalEndPoint!).Port;
    }
}

Here we are also requesting the operating system for a port by binding the loopback address to port 0.

The application itself will look like this:

using System.Net;
using System.Net.Sockets;

Console.WriteLine($"TCPListener free port: {TcpListenerGetFreePort()}");
Console.WriteLine($"Socket free port: {SocketGetFreePort()}");
return;

TLDR

You can request the operating system for an available port.

The code is in my GitHub.

Happy hacking!