Thursday, January 8, 2009

How to find an avaiable TCP port

This simple method will return the next avaiable TCP port



      private static int GetAvaiablePort()
{
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(endPoint);
IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;
return local.Port;
}
}

No comments: