17

I have tried the Request.UserHostAddress; but API controller doesn't have UserHostAddress inside Request.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1615362
  • 3,657
  • 9
  • 29
  • 46
  • 1
    Sorry, I was confused. Check this other question: http://stackoverflow.com/questions/9565889/get-the-ip-address-of-the-remote-host – Claudio Redi Sep 26 '12 at 18:06

3 Answers3

19
IP = ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
Sando
  • 667
  • 1
  • 6
  • 14
10

I am using the following code and it work for me....

string ipAddress =   System.Web.HttpContext.Current.Request.UserHostAddress;
Md. Nazrul Islam
  • 2,809
  • 26
  • 31
8

According to this, a more complete way would be:

private string GetClientIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        return ((HttpContext)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
    }
    else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
    {
        RemoteEndpointMessageProperty prop;
        prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name];
        return prop.Address;
    }
    else
    {
        return null;
    }
}

In the past, on MVC 3 projects (not API,) we used to use the following:

string IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (String.IsNullOrEmpty(IPAddress))
    IPAddress = Request.ServerVariables["REMOTE_ADDR"];
Garrett Fogerlie
  • 4,450
  • 3
  • 37
  • 56
  • 2
    I ended up doing a little extra research because it felt odd that you would pick up a request header in a server variable. context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] is picking up what is picking up the X-Forward-For request header sent by Proxy Servers and Load Balancers. – muglio May 25 '15 at 06:27
  • `HTTP_X_FORWARDED_FOR` may contain multiple addresses.You should check for that. [Example](https://stackoverflow.com/a/7348761/790465) – Igor Yalovoy Apr 24 '18 at 16:17