通过下面的代码,我能够跟踪桌面应用程序的公共IP更改。这应该能够跟踪公共IP是否更改,或者用户是否允许VPN更改其公共IP。此代码在应用程序启动时运行,并在需要检查时再次使用:
public class PublicIP
{
IPAddress last_ip=null;
DateTime timestamp_lastipchange;
public void UpdateIP()
{
List<string> hosts = new List<string>()
{
"https://api.ipify.org",
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com",
"https://wtfismyip.com/text",
"http://icanhazip.com"
};
using(WebClient webclient = new WebClient())
{
foreach(string host in hosts)
{
//Download each string from hosts until an IP could be fetched
try{
var newip = IPAddress.Parse(webclient.DownloadString(service)); //Downloading the string
if(!newip.IsEqual(last_ip) && last_ip!=null) timestamp_lastipchange = DateTime.Now; //Check if the ip changed, if the last known ip does not exists skipp this step
last_ip = newip; //Save last known ip
return;
}
catch { }
}
}
}
}
这种方法似乎运行得很好,但是在UnitTesting期间,有些工作流不会获取新的IP:
通过交换网络改变
由提供者更改的
。
我不确定工作流nr 4中发生了什么。是否必须手动选择新的网络接口(VPN)?或者这是客户机/服务器端的缓存问题吗?
发布于 2022-09-22 17:28:46
WebClient是高级的,可以在场景后面使用静态池(也不推荐)。您可以尝试使用HttpClient,因为HttpClient通过其消息处理程序处理连接,默认的连接不是静态的,这意味着这应该可以:
using(var httpClient = new HttpClient())
{
var newip = IPAddress.Parse(webclient.GetStringAsync(service)
.ConfigureAwait(false).GetAwaiter().GetResult());
// ...
}
https://stackoverflow.com/questions/73797406
复制相似问题