发布:2022/12/21 20:53:33作者:管理员 来源:本站 浏览次数:574
我想通过他的IP获取登录用户的国家。第一个功能获取IP地址。
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!");
}
第二个功能使用ip并返回国家
public class IpDTO {
public string ip { get; set; }
public string city { get; set; }
public string region { get; set; }
public string country { get; set; }
public string loc { get; set; }
public string org { get; set; }
public string timezone { get; set; }
public string readme { get; set; }
}
public static string GetUserCountryByIp(string ip)
{
try
{
IpDTO ipInfo = new IpDTO();
string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
ipInfo = JsonConvert.DeserializeObject<IpDTO>(info);
Console.WriteLine(info);
if (ipInfo != null) {
Console.WriteLine("城市:"+ipInfo.city);
Console.WriteLine("国家:" + ipInfo.country);
}
}
catch (Exception)
{
}
return "";
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4