C# - Detect public ip adress change, VPN issue

Viewed 42

With following code I am able to track public IP changes of my desktop application. This should be able to track if either the public IP changed or the user enabled a VPN to change his public IP. This code is run on application launch and used once again when a check is needed:

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 { }
                }
            }
    }

}

This approach seems to work pretty well, however during UnitTesting some workflows do not fetch a new IP:

  1. IP change by switching networks: change gets successfully detected

  2. IP changed by provider: change gets successfully detected

  3. VPN was enabled when the application was launched and is then turned off: change gets successfully detected

  4. VPN was disabled on application start and is turned on during runtime: change does not get detected. Webclient.DownloadString() still returns the same IP as if the VPN was not enabled.

I am not really sure what is happening in workflow nr 4. Do I have to manually select the new network interface (VPN)? Or is this a caching problem on the client/server side?

1 Answers

WebClient is high-level and might using static pool behind-the-scene (and also deprecated). You might try using HttpClient instead, because HttpClient handle connection via its message handler, and the default one is not static, which means this should work:

using(var httpClient = new HttpClient()) 
{
   var newip = IPAddress.Parse(webclient.GetStringAsync(service)
       .ConfigureAwait(false).GetAwaiter().GetResult()); 
   // ...
}
Related