Finding available callback tcp port for a WCF chat client

While having some fun writing a WCF chat application, I was having some troubles.

I was using duplex communication over http, using the WsDualHttpBinding. The client needs to setup a callback channel for the service to… well, call back actually. Hence the name, I guess 😉 Anyway, by default it wants to create this channel on port 80, which wasn’t possible because IIS is already listening on that port. For that you need to specify the ClientbaseAddress on your binding.

DuplexChannelFactory<IChatService> dcf = new DuplexChannelFactory<IChatService>(client, "ChatService"); Uri uri = new Uri(@"http://localhost:8000/callbackchannel"); ((WSDualHttpBinding)dcf.Endpoint.Binding).ClientBaseAddress = uri;

Now the callback channel is on port 8000.But, you might want to start multiple clients to test your service. So you need to know what port isn’t taken yet. I wasn’t the first to ask this question, but either I’m really lousy in searching Google, or nobody has blogged a complete answer yet. Either way, here’s what I used.

int selectedPort = 8000; bool goodPort = false; IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0]; // while (!goodPort) {   IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, selectedPort);   TcpListener list = new TcpListener(ipLocalEndPoint);   try   {     list.Start();     goodPort = true;     list.Stop();   }   catch   {     selectedPort++;   } }

There you go, now you know as well. Update : Was having some problems with CopySourceAsHtml after changing some settings. Should work now.