Get User Location by IP Address Using asp.net C#

Jak
Jak
Member
364 Points
152 Posts

How to get User Location by IP Address Using asp.net C#? 

Views: 8662
Total Answered: 2
Total Marked As Answer: 1
Posted On: 11-May-2016 23:15

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Moderator
1172 Points
211 Posts
         

To get geolocation on the basis of ip address you need some api. In following example I used location api from https://www.freegeoip.net 

Create a class IPLocation

public class IPLocation {
public string IPAddress { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
public string RegionCode { get; set; }
public string Region { get; set; }
public string CityCode { get; set; }
public string CityName { get; set; }
public string ISP { get; set; }
public string Organization { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string ZipCode { get; set; }
public string TimeZone { get; set; }
}

 

Create a  method GetIPLocation, will return IPLocation Object

public IPLocation GetIPLocation(string IPAddress) {
IPLocation IPLocation;
string retJson = DownloadDataNoAuth(string.Format("https://www.freegeoip.net/json/{0}", IPAddress));
var JO = JObject.Parse(retJson);
IPLocation = new IPLocation();
IPLocation.IPAddress = IPAddress;
IPLocation.CountryCode = JO["country_code"];
IPLocation.CountryName = JO["country_name"];
IPLocation.RegionCode = JO["region_code"];
IPLocation.Region = JO["region_name"];
IPLocation.CityName = JO["city"];
IPLocation.ZipCode = JO["zip_code"];
IPLocation.Latitude = JO["latitude"];
IPLocation.Longitude = JO["longitude"];
return IPLocation;
}

 

Other Method used

public string DownloadDataNoAuth(string hostURI) {
string retXml = string.Empty;
try {
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(hostURI);
request.Method = "GET";
String responseLine = String.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
using (Stream dataStream = response.GetResponseStream()) {
StreamReader sr = new StreamReader(dataStream);
retXml = sr.ReadToEnd();
sr.Close();
dataStream.Close();
}
}
} catch (Exception e) {
retXml = null;
}
return retXml;
}
 
 
public string GetIPAddress() {
return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

 You can use it as

var IPLocation = GetIPLocation("PutHereIPaddress");

 

Posted On: 12-May-2016 02:25
great..
 - nik  25-Aug-2017 00:56
xyan
xyan
12 Points
6 Posts
         

You can find location detail from the link https://www.niceonecode.com/Tools/IPLocation

Posted On: 16-Sep-2017 03:20
 Log In to Chat