Hoda Osama
Hoda Osama

Reputation: 71

how to get country by user Ip address in .Net Core?

I want to get the login-ed user country by his IP . The first function get ip address .

 public static string GetLocalIPAddress()
 {
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}

the second function takes ip and return country

 public static string GetUserCountryByIp(string ip)
    {
        IpInfo ipInfo = new IpInfo();
        try
        {
            string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
            ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
            RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
            ipInfo.Country = myRI1.EnglishName;
        }
        catch (Exception)
        {
            ipInfo.Country = null;
        }

        return ipInfo.Country;
    }

the problem here is the second function doesn't return any data . when i tried my IP at https://ipinfo.io/IP it return bogon=true .

how can i return not bogon ip.

Upvotes: 2

Views: 7057

Answers (1)

Eric Packwood
Eric Packwood

Reputation: 1059

If you are wanting to get the client's IP location, you need to use the client's IP address and not the hosts. To do this in ASP.Net Core you can do:

var clientIpAddress = request.HttpContext.Connection.RemoteIpAddress;

From there you can use clientIpAddress as the IP passed to your GetUserCountryByIp function.

Upvotes: 4

Related Questions