How to get the geographic location using IP Address in asp.net mvc

10,624

Solution 1

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.

Solution 2

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
Share:
10,624
Sumit Kesarwani
Author by

Sumit Kesarwani

Software Engineer in Trident Analytical Solutions IIT Kanpur Uttar Pradesh India Facebook ID :- sumit.kesarwani2

Updated on July 13, 2022

Comments

  • Sumit Kesarwani
    Sumit Kesarwani almost 2 years

    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.