I have a net.tcp WCF service, and I would like the OS to pick the port that it should listen on. So I have set the port to 0 in my URI, and netstat
confirms that the OS has picked a port in the 5000 range.
How can I find the actual port that has been picked, in code, inside the service process?
Some code to show what I have tried:
Type serviceType = ...;
Uri address = new Uri("net.tcp://0.0.0.0:0/Service/");
ServiceHost serviceHost = new ServiceHost(serviceType, address);
ServiceEndpoint endPoint = serviceHost.AddServiceEndpoint(type, binding, "");
int port1 = endPoint.ListenUri.Port; // returns 0
int port2 = serviceHost.BaseAddresses.First().Port; // also returns 0