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"];
- }
- }
- //varIPAddress = (System.Web.UI.Page)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"];
- }
- }
- //varIPAddress = 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)
- {
- // Machine not found...
- }
- return machineName;
- }
- }
Hope you enjoyed this blog. thanks

Rahul SinghPosted May 29, 2017, 7:50 AM
Not getting the city name ,Help me
Christopher AndrewsPosted Nov 18, 2015, 1:16 AM
Good Stuff. Thanks for sharing. We just checked out www.redfly.io. It is very easy to configure (just one line) with any .net app to track errors. Simple and nice!
Tony BravanoPosted Nov 9, 2015, 10:00 PM
This does not work in Asp.net 5 Mvc 6 beta 8. any help is much appreciated.