Is there a reliable way to test the internet connection?

Asked

Viewed 2,475 times

3

I read about the function NetworkInterface.GetIsNetworkAvailable, but it does not work in my case, since I need to check if there is really an internet connection. I also read about trying to access the Google by means of a WebClient, for example, which I thought was the most reliable way I could find, but if the page is offline (which is almost impossible), it would return to me whenever I have no internet connection, when in case I could have.

Is there any way to ensure the verification of internet connection? If not, what would be the most reliable way to test?

  • 1

    One possibility is to use the class Ping with the ips 8.8.8.8 and/or 8.8.4.4 (Google DNS servers). Other possibilities (in English) on Superuser

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);
    

Then we make the call like this:

int desc;
hasConnection = InternetGetConnectedState(out desc, 0);
  • The second way is using the ping from Windows itself, but note that it is possible that Ping may not exist or fail on certain computers (yet it is more reliable than listing networks)

    //Segunda verificação, executa ping
    hasConnection = (new Ping().Send("www.google.com").Status == IPStatus.Success) ? true : false;
    
  • In the latter case we used the same medium that Oce 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;
        }
      }
    }
    

Ai believe that the ideal version would chain the three in a decision block and check one at a time if the previous one does not exist.

  • 1

    Unfortunately the network connection tests still depend very much on OS :/ so we could never be 100% sure, but creating a cascade of possibilities we diluted the errors between them... It’s not 100% but it greatly increases reliability.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.