Thursday, October 14, 2010

Perfect way to get Client IP Address in Asp.Net

Getting visitor IP is very frequent requirement in Web Development. There are many confusion about the method to get IP in best way. First of all be aware not to use System.Net.Dns.GetHostAddresses(strHostName) method because it will always return IP Address of the local machine on which Application is running. Use the following function to get IP Address


string clientIP;
string ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Trim().Split(',');
int le = ipRange.Length - 1;
clientIP = ipRange[le];
}
else
clientIP = Request.ServerVariables["REMOTE_ADDR"];


First check HTTP_X_FORWARDED_FOR. It will give IP address of the client machine if client is using proxy server and if its null then read the IP address from Header.
Currently these are the only options available in Asp.Net. and they mostly work fine.

Note:Some times if NAT is enabled on Web server there are cases when It always pick local IP no matter what method you use. Check of NAT (Network Address Translation) for further information.
Hope this will help :). Any Suggestion, Correction and Updation is welcomed.

3 comments:

  1. when I am writting this coading in form application it gives me error that you r missing refferance but i had added all the referance but again showing me error i am new to .net world thank you in advance.


    public static string GetIPAddress()
    {

    System.Web.HttpContext context = System.Web.HttpContext.Current;
    string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (string.IsNullOrEmpty(sIPAddress))
    {
    return context.Request.ServerVariables["REMOTE_ADDR"];
    }
    else
    {
    string[] ipArray = sIPAddress.Split(new Char[] { ',' });
    return ipArray[0];
    }

    }

    ReplyDelete
  2. Dear Chetan
    I ll be glad to help you. Can you please tell me the error message and also the line of code where app is throwing error ?

    ReplyDelete
  3. i connected my phone through wifi to computer like as client i want get my mobile ip or mac address so please help me .this is my id vettri.it@gmail.com

    regards
    -Vettri

    ReplyDelete