tags:

views:

444

answers:

3

Related to http://stackoverflow.com/questions/391142/how-to-get-the-ip-address-of-a-wcf-remote-endpoint

I am using this code to retrieve the remote IP address when a workflow method is invoked:

private static string GetRemoteIP()
{
  var oc = OperationContext.Current;
  var mp = oc.IncomingMessageProperties;
  var remp = mp[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

  return remp == null ? "(unknown)" : remp.Address;
}

However, the address I get back is "::1". I don't want the IPv6 address, I want the IPv4 one (127.0.0.1) - any way of forcing this?

+1  A: 

No, I don't think so. You basically just read out a property set by the client at the time of the call. Your only option would be to instruct the client (through some config) to use IPv4 instead of IPv6 at all times (i.e. turn off IPv6 all together).

I'm not aware of any WCF setting to enforce that - you'd have to dig into the network stack and see if there's any way to make it use IPv4 addresses instead of IPv6.

marc_s
:( Ok, I guess that's it then.
Marcel Popescu
+2  A: 

Here is a workaround: (You can store the values in a hashtable to avoid multiple DNS operations)

    static string GetClientIP()
    {
        var context = OperationContext.Current;
        var mp = context.IncomingMessageProperties;
        var propName = RemoteEndpointMessageProperty.Name;
        var prop = (RemoteEndpointMessageProperty) mp[propName];
        string remoteIP = prop.Address;

        if(remoteIP.IndexOf(":") < -1)
        {
            IPAddress[] addresses = Dns.GetHostAddresses(remoteIP);
            for (int i = 0; i < addresses.Length; i++)
            {
                if(addresses[i].ToString().IndexOf(".")>-1)
                    return addresses[i].ToString();
            }
            return remoteIP;
        }
        else
        {
            return remoteIP;
        }
    }
Murat Eraydin
+1  A: 

You're seeing ::1 because you're connecting to the service by resolving the name "localhost" instead of addressing it as "127.0.0.1". Modern versions of Windows that have the IPv6 stack enabled will use IPv6 first.

You can disable the IPv6 stack, but that's roughly the same as making like an ostrich and sticking your head in the sand. IPv6 is here, and people are using it on their networks, so your application should be prepared to support it.

Warren