Reputation: 573
I know that this code:
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = Request.ServerVariables["REMOTE_ADDR"];
}
will give me the IP Address of the user but I don't know how to get the location of the user
I want to know the location and related information on basis of IP Address.
Upvotes: 6
Views: 12452
Reputation: 2032
This answer for people is searching in 2022 :).
You can use ip3country-dotnet. It is small library <500KB. This library is using ip2location the lite version, it is totally free!.
Way of usage:
Install IP3Country
, then write this code
// Lookup using ip4 str
var country = CountryLookup.LookupIPStr("123.45.67.8"); // => 'KR'
// Lookup using numeric ip
country = CountryLookup.LookupIPNumber(2066563848); // => 'KR'
Upvotes: 1
Reputation: 1560
Model to bind the user location details
public class IpInfo
{
[JsonProperty("ip")]
public string Ip { get; set; }
[JsonProperty("city")]
public string City { get; set; }
[JsonProperty("region_name")]
public string Region { get; set; }
[JsonProperty("country_name")]
public string Country { get; set; }
[JsonProperty("time_zone")]
public string TimeZone { get; set; }
[JsonProperty("longitude")]
public string Longitude { get; set; }
[JsonProperty("latitude")]
public string Latitude { get; set; }
}
Function
private IpInfo GetUserLocationDetailsyByIp(string ip)
{
var ipInfo = new IpInfo();
try
{
var info = new WebClient().DownloadString("http://freegeoip.net/json/" + ip);
ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
}
catch (Exception ex)
{
//Exception Handling
}
return ipInfo;
}
Calling function with IP value
var ipDetails = GetUserCountryByIp("8.8.8.8"); //IP value
Upvotes: 4
Reputation: 2220
This should help you - http://freegeoip.net/
freegeoip.net is a public REST API for searching geolocation of IP addresses and host names. Send HTTP GET requests to: freegeoip.net/{format}/{ip_or_hostname}. The API supports both HTTP and HTTPS and Supported formats are csv, xml or json.
Upvotes: 8