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
{
}
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.UserHostAddressproperty follows:Note that it returns
_wr.GetRemoteAddress(). The_wrvariable is an instance of anHttpWorkerRequestobject. There are different classes derived fromHttpWorkerRequestand 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 forGetRemoteAddress(), namely:As you can see,
GetRemoteAddress()simply returns the server variableREMOTE_ADDR.As far as which one to use, I’d suggest the
UserHostAddressproperty since is doesn’t rely on “magic strings.”Happy Programming