Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Request.UserHostAddress and Request.ServerVariables["REMOTE_ADDR"].ToString()

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     {      } 
like image 302
MonsterMMORPG Avatar asked Dec 21 '12 17:12

MonsterMMORPG


People also ask

What is request ServerVariables Remote_addr?

ServerVariables("REMOTE_ADDR") is Always the Same. If your scripts use Request. ServerVariables("REMOTE_ADDR") to get the client's IP address, they will always show the same, internal IP address due to the load balancers used for hosting your site. You can get the client's remote IP using Request.

How do I get UserHostAddress in .NET core?

HttpRequest. UserHostAddress gives the IP address of the remote client. In ASP.NET Core 1.0, you have to use the HTTP connection feature to get the same. HttpContext has the GetFeature<T> method that you can use to get a specific feature.


1 Answers

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

like image 129
Scott Mitchell Avatar answered Sep 24 '22 08:09

Scott Mitchell