Powered By Blogger

Wednesday, February 27, 2013

Getting client IP Address in C#

Here is a function where i am getting client's IP address  

Solution 1:
 public static string GetClientIP(HttpRequest Request)
    {
        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"];
        }
        return clientIP;
    }

Solution 2:

private string GetIP()
    {
        string strHostName = "";
        strHostName = System.Net.Dns.GetHostName();
 
        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
 
        IPAddress[] addr = ipEntry.AddressList;
 
        return addr[addr.Length - 1].ToString();
 
    }