Here, in this blog I will explain you how to get IP address and location of visitors who are accessing your web page on the internet.

Actually Internet protocol is used to track the system and provide use system host and system IP and location. To use this code you can just figure out from where and from which IP address my site is being accessed.

For this you need to create a static class where you will get Visitor Details and location as well.

  1. public class IPHostGenerator
  2. {
  3. internal string GetCurrentPageUrl()
  4. {
  5. return HttpContext.Current.Request.Url.AbsoluteUri;
  6. }
  7. internal string GetVisitorDetails()
  8. {
  9. string varIPAddress = string.Empty;
  10. string varVisitorCountry = string.Empty;
  11. string varIpAddress = string.Empty;
  12. varIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  13. if (string.IsNullOrEmpty(varIpAddress))
  14. {
  15. if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
  16. {
  17. varIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  18. }
  19. }
  20. //varIPAddress = (System.Web.UI.Page)Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  21. if (varIPAddress == "" || varIPAddress == null)
  22. {
  23. if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
  24. {
  25. varIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  26. }
  27. }
  28. //varIPAddress = Request.ServerVariables["REMOTE_ADDR"];
  29. return varIpAddress;
  30. }
  31. internal DataTable GetLocation(string varIPAddress)
  32. {
  33. WebRequest varWebRequest = WebRequest.Create("http://freegeoip.net/xml/" + varIPAddress);
  34. WebProxy px = new WebProxy("http://freegeoip.net/xml/" + varIPAddress, true);
  35. varWebRequest.Proxy = px;
  36. varWebRequest.Timeout = 2000;
  37. try
  38. {
  39. WebResponse rep = varWebRequest.GetResponse();
  40. XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());
  41. DataSet ds = new DataSet();
  42. ds.ReadXml(xtr);
  43. return ds.Tables[0];
  44. }
  45. catch
  46. {
  47. return null;
  48. }
  49. }
  50. internal string GetMachineNameUsingIPAddress(string varIpAdress)
  51. {
  52. string machineName = string.Empty;
  53. try
  54. {
  55. IPHostEntry hostEntry = Dns.GetHostEntry(varIpAdress);
  56. machineName = hostEntry.HostName;
  57. }
  58. catch (Exception ex)
  59. {
  60. // Machine not found...
  61. }
  62. return machineName;
  63. }
  64. }

Hope you enjoyed this blog. thanks