This is the technical blog of Keyvan Nayyeri, a 29 years old software engineer at Match.Com, speaker and author. You will find content about computer science, programming, and technology on here.
One of the features that was missing from WCF 3.0 was the ability to detect client IP address in services. For a technology that is completely built on top of SOA hence a server/client mechanism where clients are an important part of the story this looked like a big lack!
There are various situations where you need to retrieve the client IP address on your service side and there is no doubt that having such a feature can be a common need and request.
However, this is a new feature added to .NET 3.5 and Windows Communication Foundation 3.5 for developers and you're now able to retrieve the client's IP address and port in your code easily.
Suppose that I have a service contract like what you see below where there is a single method to get a string argument and return another string value.
Here comes the implementation of this service contract with a very simple code that returns a string including the client's IP address and port.
You simply can notice that there are a few steps to retrieve the client information from the OperationContext. First you need to get access to the current instance of the OperationContext then retrieve its IncomingMessageProperties as a MessageProperties object. The last step is to create an instance of RemoteEndpointMessageProperty by looking in the MessageProeprties collection for the name of the RemoteEndpointMessageProperty. Now RemoteEndpointMessageProperty has two separate properties to get access to the client's IP address and port.
It's worthwhile to know that behind the scenes WCF is passing the client's IP and port (along some other information) with each message as the properties for the message. This is happening for services hosted on HTTP or TCP protocols so the important point is here and you can't apply this code for other protocols.
I can self-host this service with a simple configuration file that is already generated by Visual Studio 2008 and just needs some modifications to apply new contract and service names.
Hosting and running the service, I can test it quickly to get an output like what you see here:
You can download the source code sample for this post from here.