Available TCP port with C #

How can I examine the available TCP port for programmatically configuring WCF Service EndPoint?

+5
source share
3 answers

How will your client know about the endpoint if you dynamically select your server port?

Anyway,

Here is a dirty way to discover an open port

 for (int port = 2000; port < 65535; port++) 
                   {
                   IPEndPoint ep = new IPEndPoint(IPAddress.Any, port);
                   Socket socket = new Socket(AddressFamily.InterNetwork, st, pt);

                   try { 
                         socket.Bind(ep);
                         socket.Close();  
                         //Port available
                        } 
                   catch (SocketException)
                        {
                        Debug.WriteLine("Port not available {0}", port);
                        } 

                   }

And then try creating your own service host.

http://msdn.microsoft.com/en-us/library/aa395224.aspx

+3
source

Not a particularly elegant way, but you can just try opening the host and catching the exceptions AddressAlreadyInUseException. This excludes the use Socketand race conditions that are present in the amazedsaint method: nothing can take the port between the check and your attempt to open the service.

, :

ServiceHost host;

for(int port = 2000; port < 65535; port++) {
    var address = GetBaseAddress(port);
    host = new ServiceHost(typeof(MyService), address);
    try {
        host.Open();
        break;
    }
    catch(AddressAlreadyInUseException) {

    }
}

GetBaseAddress String.Format, .

, , WCF Discovery .NET 4.

0
0
source

All Articles