Search code examples
c#wcfwcf-data-services

Self Hosted WCF Data Service - Specify IP Address to Listen on?


I've written a WCF Data Service that is self hosted in a Windows console application.

The service is initialised with the following code:

static void Main(string[] args)
{
    DataServiceHost host;

    Uri[] BaseAddresses = new Uri[] { new Uri("http://12.34.56.78:9999")};

    using (host = new DataServiceHost( typeof( MyServerService ), BaseAddresses ) )
    {
        host.Open(); 
        Console.ReadLine();
    }
}

When I run this, the console app runs and appears to listen on 0.0.0.0:9999 and not 12.34.56.78:9999.

Does this mean that the service is listening on all IP addresses?

Is there a way I can get the service to only listen on the IP specified (12.34.56.67:9999)?

Thanks


Solution

  • To specify the listen IP, you must use the HostNameComparisonMode.Exact. For example, the code below prints the following in NETSTAT:

    C:\drop>netstat /a /p tcp
    
    Active Connections
    
      Proto  Local Address          Foreign Address        State
      TCP    10.200.32.98:9999      Zeta2:0                LISTENING
    

    From code:

    class Program
    {
        static void Main(string[] args)
        {
            Uri[] BaseAddresses = new Uri[] { new Uri("http://10.200.32.98:9999") };
            using (var host = new ServiceHost(typeof(Service), BaseAddresses))
            {
                host.AddServiceEndpoint(typeof(Service), new BasicHttpBinding() { HostNameComparisonMode = HostNameComparisonMode.Exact }, "");
    
                host.Open();
                Console.ReadLine();
            }
        }
    }
    
    [ServiceContract]
    class Service
    {
        [OperationContract]
        public void doit()
        {
        }
    }
    

    From config:

    <basicHttpBinding>
        <binding name="yourBindingName" hostNameComparisonMode="Exact" />
    </basicHttpBinding>