Reputation: 71
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
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