Finding the Remote Client Address

After being a highly-requested feature, back in .Net 3.5 we added the ability to see the network address from which the client request had arrived. Here's how it works.

Participating transports capture the client's network address using whatever sources of information they have available. The transport then attaches a message property to the received message that allows the service to access the address.

You can access the client address through any mechanism for looking at the message properties attached to the message. For example, in a service operation you might do something like this:

 OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty

The message property then gives you direct access to the client address. Most transports are expected to put the hostname in the Address field and the socket port number in the Port field but transport implementations are free to format the address differently if they ordinarily have some special convention to their addresses.

 public sealed class RemoteEndpointMessageProperty
{
    public RemoteEndpointMessageProperty(string address, int port);

    public string Address { get; }
    public int Port { get; }

    public static string Name { get; }
}

If the transport doesn't capture client addresses or the address isn't available, then the message property won't be present. There are many reasons why the client address might not be available. For example, for an HTTP service hosted in IIS the address is discarded once the connection is closed.

You can decide what to do about a missing client address depending on how you're planning to use it. What you shouldn't use it for is making security decisions. It's possible in some cases for a malicious client to spoof the address detected by the server.