Dan Rigsby - Coding Up Style

.Net, C#, & Wcf Development

Get the Client’s Address in WCF

Posted by Dan Rigsby on May 21st, 2008

In .Net 3.0 there was not a reliable way to obtain the address of the client connecting to a WCF service.  In .Net 3.5 a new property was introduced called RemoteEndpointMessageProperty.  This property gives you the IP address and port that the client connection came into the service on. Obtaining the this information is pretty straight forward.  Just pull it from the IncomingMessageProperties of the current OperationContext by the RemoteEndpointMessageProperty.Name and access the Address and Port properties.

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string GetAddressAsString();
}

public class MyService : IMyService
{
    public string GetAddressAsString()
    {
        RemoteEndpointMessageProperty clientEndpoint =
            OperationContext.Current.IncomingMessageProperties[
            RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

        return String.Format(
            "{0}:{1}",
            clientEndpoint.Address, clientEndpoint.Port);
    }
}

Things to note:

  1. This property only works on http and tcp transports.  On all other transports such as MSMQ and NamedPipes, this property will not be available.
  2. The address and port are reported by the socket or http.sys of the service’s machine.  So if the client came in over a VPN or some other proxy that modified the address, that new address will be represented instead of the client’s local address.  This is desirable and important because this is the address and port that the service sees the client as, not as the client sees itself as.  This also means that there could be some spoofing going on.  A client or something in between the client and server could spoof an address. So, do not use the address or port for any security decisions unless you add in some other custom checking mechanisms.
  3. If you are using duplexing on your service, then not only will the service have this property populated for the client, but the client will also have this property populated for the service for each call from that service.

You can download a sample service using this code here: http://www.danrigsby.com/Files/Rigsby.WcfClientAddress.zip

2 Responses to “Get the Client’s Address in WCF”

  1. Dew Drop - May 22, 2008 | Alvin Ashcraft's Morning Dew Says:

    [...] Get the Client’s Address in WCF (Dan Rigsby) [...]

  2. Dan Rigsby » Get the Service Endpoint address a Client is accessing in WCF Says:

    [...] a previous post I talked about how to get the address of a client accessing a WCF service.  I got a few [...]

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>