C# – Getting caller’s hostname in WCF

c++dnswcfwcf-security

I'm replacing an existing web service with a WCF service and as the first step of migration I'm going to expose an endpoint with BasicHttpBinding until the client is upgraded later on in the year.

The plan is to host the new WCF service with a windows service (the service will only be called from within the intranet so there's no real need for HTTP), but exposing both Basic HTTP and Net.TCP endpoints so that the migration can happen in stages.

However, I'm having some trouble getting the caller's hostname in my WCF service, looking at the current web service code it's using Context.Request.UserHostName to get the hostname. I've managed to get the caller's username and IP address but all the related permission/security services in the environment uses the hostname as opposed to IP, so is there any way for me to get the HostName inside my service?

P.S. I've set the security mode to TransportCredentialOnly with clientCredientialType set to Windows

Best Solution

Since you are not hosting in IIS, you can't use ASP.NET compatibility mode to get access to the HttpContext which would normally be present in an ASP.NET process.

Instead, you can use the GetHostEntry method on the Dns class in the System.Net namespace to get the IPHostEntry instance which will contain the aliases (DNS names) for the IP addresses that you are obtaining.