Get User Location by IP Address Using asp.net C#
Jak
908
Points
132
Posts
|
How to get User Location by IP Address Using asp.net C#? |
Answers
Rahul M...
4918
Points
28
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
78
Points
3
Posts
|
You can find location detail from the link https://www.niceonecode.com/Tools/IPLocation
Posted On:
16-Sep-2017 03:20
|
Blog
Active User (0)
No Active User!