Obtaining client IP address in WCF 3.0

Apparently you can easily obtain a client IP address in WCF 3.5 but not in WCF 3.0. Anyone know how?


Solution 1:

This doesn't help you in 3.0, but I can just see people finding this question and being frustrated because they are trying to get the client IP address in 3.5. So, here's some code which should work:

using System.ServiceModel;
using System.ServiceModel.Channels;

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
    prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;

Solution 2:

It turns out you can, so long as (a) your service is being hosted in a Web Service (obviously) and (b) you enable AspNetCompatibility mode, as follows:

    <system.serviceModel>
            <!-- this enables WCF services to access ASP.Net http context -->
            <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
...
    </system.serviceModel>

And then you can get the IP address by:

HttpContext.Current.Request.UserHostAddress

Solution 3:

You can if you are targeting .NET 3.0 SP1.

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;

Credits: http://blogs.msdn.com/phenning/archive/2007/08/08/remoteendpointmessageproperty-in-wcf-net-3-5.aspx

Reference: http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx