48

Here I can use either of these 2 methods. What are the differences and which one should I use?

Method 1:

    string srUserIp = "";
    try
    {
        srUserIp = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
    }
    catch
    {

    }

Method 2:

    string srUserIp = "";
    try
    {
        srUserIp = Request.UserHostAddress.ToString();
    }
    catch
    {

    }
tshepang
  • 12,111
  • 21
  • 91
  • 136
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • these won't produce same results if the user has a proxy server, will it? Method 2 will get proxy's address instead of user's machine. I won't use method 2 over method 1. – Laurence Sep 17 '13 at 11:25
  • just need to let know who is reading this, this is causing problems. so i am not using anymore. – Furkan Gözükara Sep 23 '13 at 11:12
  • @MonsterMMORPG, which of methods causing problems, and what are the problems? – Michael Freidgeim May 01 '14 at 04:59
  • possible duplicate of [What is the difference between Request.ServerVariables\["REMOTE\_ADDR"\] and Request.UserHostAddress?](http://stackoverflow.com/questions/6537482/what-is-the-difference-between-request-servervariablesremote-addr-and-reques) – theycallmemorty May 02 '14 at 19:48

2 Answers2

71

Short answer: The two are identical.

Long answer: To determine the difference between the two use Reflector (or whatever disassembler you prefer).

The code for the HttpRequest.UserHostAddress property follows:

public string UserHostAddress
{
    get
    {
        if (this._wr != null)
        {
            return this._wr.GetRemoteAddress();
        }
        return null;
    }
}

Note that it returns _wr.GetRemoteAddress(). The _wr variable is an instance of an HttpWorkerRequest object. There are different classes derived from HttpWorkerRequest and which one is used depends on whether you are using IIS 6, IIS 7 or beyond, and some other factors, but all of the ones you would be using in a web application have the same code for GetRemoteAddress(), namely:

public override string GetRemoteAddress()
{
    return this.GetServerVariable("REMOTE_ADDR");
}

As you can see, GetRemoteAddress() simply returns the server variable REMOTE_ADDR.

As far as which one to use, I'd suggest the UserHostAddress property since is doesn't rely on "magic strings."

Happy Programming

Mike Brind
  • 28,238
  • 6
  • 56
  • 88
Scott Mitchell
  • 8,659
  • 3
  • 55
  • 71
6

There is no difference. They return exactly the same value. However, one is IntelliSense-friendly whereas the other is not.

Mike Brind
  • 28,238
  • 6
  • 56
  • 88