Get Client IP address and location in asp.net C#

public string GetIPAddress()
{
    string ipAddress = string.Empty;
    ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if(string.IsNullOrEmpty(ipAddress))
  {
        ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        ipAddress = ipAddress.Replace("::ffff:", "");
        ipAddress = ipAddress.Replace("::1", "");
  }
    return ipAddress;
}
public string GetIPLocation()
{
    string address = string.Empty;
    string ipAddress = GetIPAddress();
    string xmlString = IPRequestHelper("http://ip-api.com/xml/" + ipAddress);
    if(string.IsNullOrEmpty(xmlString))
  {
        XmlDocument xdoc = new XmlDocument();
        xdoc.LoadXml(xmlString);
        XmlNode statusNode = xdoc.SelectSingleNode("/query/" + "status");
        if (statusNode.InnerText == "success")
    {
            XmlNode cityNode = xdoc.SelectSingleNode("/query/" + "city");
            XmlNode regionNameNode = xdoc.SelectSingleNode("/query/" + "regionName");
            XmlNode regionNode = xdoc.SelectSingleNode("/query/" + "region");
            XmlNode countryNode = xdoc.SelectSingleNode("/query/" + "country");
            XmlNode countryCodeNode = xdoc.SelectSingleNode("/query/" + "countryCode");
 
            address = cityNode.InnerText + ", ";
            address += regionNameNode.InnerText + " (" + regionNode.InnerText + "), ";
            address += countryNode.InnerText + " (" + countryCodeNode.InnerText + ")";
    }
  }
    return address;
}
public string IPRequestHelper(string url)
{
    string responseRead = string.Empty;
    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
    StreamReader responseSteam = new StreamReader(objResponse.GetResponseStream());
    responseRead = responseSteam.ReadToEnd();
    responseSteam.Close();
    responseSteam.Dispose();
    return responseRead;
}
Note: You can not get IP address on local host.

 Posted Comments

No comments have been posted to this article.

 Post a comment

Name:
Email:
Comment:
Security Code:
25 + 84
=
We don't publish your email on our website.