Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get client IP address in self-hosted SignalR hub

Tags:

signalr

How do you go about getting the IP address of the remote client in a self-hosted SignalR hub? According to this question, you could at one point get it using Context.ServerVariables[], but that seems to be missing from the latest version of SignalR.

like image 922
Ken Smith Avatar asked Dec 15 '12 04:12

Ken Smith


2 Answers

Well, in poking around in the recent commits on the SignalR project (specifically this one), I spotted how to do it.

protected string GetIpAddress()
{
    var env = Get<IDictionary<string, object>>(Context.Request.Items, "owin.environment");
    if (env == null)
    {
        return null;
    }
    var ipAddress = Get<string>(env, "server.RemoteIpAddress");
    return ipAddress;
}

private static T Get<T>(IDictionary<string, object> env, string key)
{
    object value;
    return env.TryGetValue(key, out value) ? (T)value : default(T);
}
like image 89
Ken Smith Avatar answered Oct 17 '22 01:10

Ken Smith


I didn't try it with the self-hosted SignalR Hub, but with SignalR 2.0, Context.Request doesn't have the Items anymore (at least not what I saw). I figured out, how it works now. (You can reduce the if / else part to a ternary operator, if you like that.)

protected string GetIpAddress()
{
    string ipAddress;
    object tempObject;

    Context.Request.Environment.TryGetValue("server.RemoteIpAddress", out tempObject);

    if (tempObject != null)
    {
        ipAddress = (string)tempObject;
    }
    else
    {
        ipAddress = "";
    }

    return ipAddress;
}
like image 32
Micky Avatar answered Oct 16 '22 23:10

Micky