2

I'm using multiple self-hosted WCF services on the same machine. I need to open each of them on a different port (obviously), so I used "net:tcp://localhost:0" as address since I figured it would assign a free port this way.

Now I need to know which port was assigned actually. This code runs on the server, so I need the local port. How do I do that?

mafu
  • 31,798
  • 42
  • 154
  • 247
  • 1
    http://stackoverflow.com/questions/3563393/how-can-i-get-the-port-that-a-wcf-service-is-listening-on – keza Apr 18 '12 at 05:30
  • possible duplicate of [How can I get the listening address/port of a WCF service?](http://stackoverflow.com/questions/2207348/how-can-i-get-the-listening-address-port-of-a-wcf-service) – mafu Apr 18 '12 at 11:08

3 Answers3

2

You can use OperationContext.Channel.LocalAddress.Uri.Port to know the port used in the call to a service

CriGoT
  • 994
  • 7
  • 12
  • 1
    Is there a way to do it outside the service itself (in the console host code)? I don't have an OperationContext there. – mafu Aug 12 '10 at 12:43
0

Then you need another place to store all service's ports to read them from outside the server. If it's another service, then it needs a constant port. It also can be a xml file over http or something modified on each of service's startup.

More on WCF Discovery

Wojtek Turowicz
  • 4,086
  • 3
  • 27
  • 38
0

Found something that works, even though it is a bit dirty. Instead of automatically assigning a port, a free port is explicitly requested and used to create the service:

Address = "net.tcp://localhost:" + FindFreeTcpPort ();

private static int FindFreeTcpPort ()
{
    TcpListener l = new TcpListener (IPAddress.Parse ("127.0.0.1"), 0);
    l.Start ();
    int port = ((IPEndPoint) l.LocalEndpoint).Port;
    l.Stop ();
    return port;
}

(the method code is from here)

Community
  • 1
  • 1
mafu
  • 31,798
  • 42
  • 154
  • 247
  • 2
    Since I got no new responses I'll accept this solution even though I don't like it. – mafu Aug 25 '10 at 12:17