When working with network programming in .NET, you may need to find an available port on your system. This is particularly useful for server applications, running tests, or developing tools that need to bind to a network port without conflicts.
Here's a simple way to get an available port using the Socket class:
C#
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(IPEndPoint.Parse("127.0.0.1:0"));
var port = ((IPEndPoint)s.LocalEndPoint).Port;
s.Close();
Setting the port to 0 tells the operating system to assign an available port automatically. After binding, you can retrieve the assigned port from the LocalEndPoint property of the socket.
Do you have a question or a suggestion about this post? Contact me!