Is there a reliable way to test your internet connection?

3

I read about the NetworkInterface.GetIsNetworkAvailable , but it does not work in my case, since I need to check if there is actually an internet connection. I also read about trying to access the Google page through a

asked by anonymous 06.09.2016 / 04:46

1 answer

3

There is no "right way", although the use of network interfaces can be really useful and valid, it is not 100% reliable, since it is possible that network interfaces vary from user to user. >

What I usually do is a "cascade" of attempts.

  • The first attempt is through a Windows DLL that is imported into the code:

    [System.Runtime.InteropServices.DllImport("wininet.dll")]
    private static extern bool InternetGetConnectedState(out int Description, int ReservedValue);
    

So we call it like this:

int desc;
hasConnection = InternetGetConnectedState(out desc, 0);
  • The second way is to use ping of Windows itself, but note that it is possible that Ping may not exist or otherwise fail on certain computers (it is still more reliable than the network listing)

    //Segunda verificação, executa ping
    hasConnection = (new Ping().Send("www.google.com").Status == IPStatus.Success) ? true : false;
    
  • Then in the latter case we use the same medium you used:

    //Checa adaptadores de rede
    if (NetworkInterface.GetIsNetworkAvailable())
    {
      //Busca todos os adaptadores de rede
      foreach (NetworkInterface network in NetworkInterface.GetAllNetworkInterfaces())
      {
        if (network.OperationalStatus == OperationalStatus.Up && network.NetworkInterfaceType != NetworkInterfaceType.Tunnel && network.NetworkInterfaceType != NetworkInterfaceType.Loopback)
        {
         hasConnection = true;
        }
        else
        {
         hasConnection = false;
        }
      }
    }
    

I believe that the ideal version would be to chain all three into a decision block and check one at a time if the previous one does not exist.

    
06.09.2016 / 12:28