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.
- public class IPHostGenerator
- {
- internal string GetCurrentPageUrl()
- {
- return HttpContext.Current.Request.Url.AbsoluteUri;
- }
- internal string GetVisitorDetails()
- {
- string varIPAddress = string.Empty;
- string varVisitorCountry = string.Empty;
- string varIpAddress = string.Empty;
- varIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
- if (string.IsNullOrEmpty(varIpAddress))
- {
- if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
- {
- varIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
- }
- }
-
-
- if (varIPAddress == "" || varIPAddress == null)
- {
- if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
- {
- varIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
- }
- }
-
- return varIpAddress;
- }
-
- internal DataTable GetLocation(string varIPAddress)
- {
- WebRequest varWebRequest = WebRequest.Create("http://freegeoip.net/xml/" + varIPAddress);
- WebProxy px = new WebProxy("http://freegeoip.net/xml/" + varIPAddress, true);
- varWebRequest.Proxy = px;
- varWebRequest.Timeout = 2000;
- try
- {
- WebResponse rep = varWebRequest.GetResponse();
- XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());
- DataSet ds = new DataSet();
- ds.ReadXml(xtr);
- return ds.Tables[0];
- }
- catch
- {
- return null;
- }
- }
-
- internal string GetMachineNameUsingIPAddress(string varIpAdress)
- {
- string machineName = string.Empty;
- try
- {
- IPHostEntry hostEntry = Dns.GetHostEntry(varIpAdress);
-
- machineName = hostEntry.HostName;
- }
- catch (Exception ex)
- {
-
- }
- return machineName;
- }
- }
Hope you enjoyed this blog. thanks