Freigeben über


Client IP addresses in Orcas

As Nicholas promised, here is some more information about client IP address in Orcas.

In the Orcas release of WCF, we added the ability for services to get the IP address and port of the calling client from your service methods when the underlying transport is Http or Tcp.

You can access the address and port as follows:

 namespace Sample
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Net;

    [ServiceContract]
    interface IMyService
    {
        [OperationContract]
        public string ProcessUntyped(Message message);
        [OperationContract]
        public string ProcessTyped(string str);
    }

    class MyService : IMyService
    {
        public string ProcessUntyped(Message message)
        {
            RemoteEndpointMessageProperty endpoint = message.Properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            return string.Format("Connected from {0}:{1}", str, endpoint.Address, endpoint.Port);
        }

        public string ProcessTyped(string str)
        {
            OperationContext context = OperationContext.Current;
            MessageProperties properties = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            return string.Format("You said: '{0}'. Connected from {1}:{2}", str, endpoint.Address, endpoint.Port);
        }
    }
}

Note, if you are using the channel model directly, you can just look at Message.IncomingMessageProperties for the RemoteEndpointMessageProperty

If you are developing your own transport channel, you can attach the property to messages received through your transport channel:

 public RemoteEndpointMessageProperty(string address, int port); 

The address specified must be a non zero-length sting and the port should be from 0-65535.

Some additional things to consider:

  1. The IP address and port are as reported from the underlying socket or http.sys and is from the connected machine, so it may be a proxy address.
  2. We don't do any sort of spoof detection, so be careful about using the IP for any sort of security decisions.
  3. For all transports other then http and net.tcp the property will not be on the message.
  4. If you are using composite duplex, the property will be available on the client on replies from the service.

Comments

  • Anonymous
    September 13, 2007
    This is so helpful, thanks so much!

  • Anonymous
    April 28, 2008
    I've had scattered posts in the past talking about the messaging features and enhancements in Orcas.