How can I get the port that the WCF service is listening on?

I have a WCF net.tcp service, and I would like the OS to select the port that it should listen on. So I set the port to 0 in my URI, and netstat confirms that the OS has selected a port in the range of 5000.

How can I find the actual port that was selected in the code inside the maintenance process?

Some code to show that I 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 
+7
c # service wcf
Aug 25 '10 at 6:38
source share
3 answers

Not sure if this will help, but there is a similar question already on SO: How to get the listening address / port of a WCF service?

Relevant part of the provided answer that you can try:

 foreach (var channelDispatcher in serviceHost.ChannelDispatchers) { Console.WriteLine(channelDispatcher.Listener.Uri); } 

So, you may need channelDispatcher.Listener.Uri.Port .

Hope this helps!

+10
Aug 25 '10 at 6:53
source share

After starting the service, you can get a full description of the endpoints that were actually created from the Description.Endpoints collection (this does not work until Open () is called). From this collection you can get the address. Unfortunately, you need to do a string analysis of the address for the port.

This is what my server registers after every Open () service.

  serviceHost.Open(); // Iterate through the endpoints contained in the ServiceDescription System.Text.StringBuilder sb = new System.Text.StringBuilder(string.Format("Active Service Endpoints:{0}", Environment.NewLine), 128); foreach (ServiceEndpoint se in serviceHost.Description.Endpoints) { sb.Append(String.Format("Endpoint:{0}", Environment.NewLine)); sb.Append(String.Format("\tAddress: {0}{1}", se.Address, Environment.NewLine)); sb.Append(String.Format("\tBinding: {0}{1}", se.Binding, Environment.NewLine)); sb.Append(String.Format("\tContract: {0}{1}", se.Contract.Name, Environment.NewLine)); foreach (IEndpointBehavior behavior in se.Behaviors) { sb.Append(String.Format("Behavior: {0}{1}", behavior, Environment.NewLine)); } } Console.WriteLine(sb.ToString()); 
+3
Aug 26 '10 at 15:00
source share

Alternatively, you can find a free port for WCF to use on your own:

 private int FindPort() { IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0); using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(endPoint); IPEndPoint local = (IPEndPoint)socket.LocalEndPoint; return local.Port; } } 

The code is here .

+1
Aug 25 '10 at 7:05
source share



All Articles