How to Find an Available Network Port for a server in .NET
When working with network programming in .NET, you might need to find an available port on your system. This is particularly useful when creating 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();
Note that the port is set to 0
, which 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!
Enjoy this blog?
💖 Sponsor on GitHub