How To Get The IP Address of Users using ASP .Net


If you want to track or analyze who is accessing your website, you can easily do this by capture the IP address of an incoming connection to your aspx page.
Here is the Code to access user's IP Address

Label1.Text = Request.ServerVariables["REMOTE_ADDR"];

4 comments:

  1. i am using following to get IP address of user who is using my webservice

    Context.Request.UserHostAddress

    ReplyDelete
  2. They both seems the same, however i think ["REMOTE_ADDR"] is faster see :-
    http://forums.asp.net/p/1361334/2812402.aspx

    ReplyDelete
  3. but why ["REMOTE_ADDR"] is faster than "Context.Request.UserHostAddress"??? can you explain the reason. you are only checking its execution time.

    ReplyDelete
  4. Salman so far I have not gone in details but here is the code through which i tested and REMOVE_ADDR approach is talking half the time then Context.Request.UserHostAddress

    Stopwatch sw = new Stopwatch();

    sw.Start();
    for (int i = 0; i < 100000; i++)
    {
    string s = Context.Request.UserHostAddress;
    }
    sw.Stop();

    double total1= sw.Elapsed.TotalMilliseconds; // Taking around 330 Milisecs

    sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < 100000; i++)
    {
    string s = Context.Request.ServerVariables["REMOTE_ADDR"];
    }
    sw.Stop();

    double total2 = sw.Elapsed.TotalMilliseconds; // Taking around 120 Milisecs

    Need to perform some more RnD that why UserHostAddress is slower.

    ReplyDelete