title: How can I get the port that a WCF service is listening on?
body: <p>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 <code>netstat</code> confirms that the OS has picked a port in the 5000 range.</p>
  
  <p>How can I find the actual port that has been picked, in code, inside the service process? </p>
  
  <p>Some code to show what I have tried:</p>
  
  <pre><code>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
  </code></pre>