Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is GetIsNetworkAvailable() always returning true?

I have this method:

public static void testConnection()
    {
        if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
        {
            System.Windows.MessageBox.Show("This computer is connected to the internet");
        }
        else
        {
            System.Windows.MessageBox.Show("This computer is not connected to the internet");
        }
    }

I suppose it would tell me whether the connection is available or not but it always return true (and print the 1st message) even when I'm sure there is no connection. What I'm doing wrong?

P.S.: I'm still learning C#.

like image 681
Rodrigo Guedes Avatar asked Nov 19 '12 15:11

Rodrigo Guedes


3 Answers

I think this method is more appropriate:

   public static bool getIsInternetAccessAvailable()
    {
        switch(NetworkInformation.GetInternetConnectionProfile().GetNetworkConnectivityLevel())
        {
            case NetworkConnectivityLevel.InternetAccess:
                return true;
            default:
                return false;
        }
    }
like image 186
ventura8 Avatar answered Oct 23 '22 03:10

ventura8


Please correct me if I am wrong but as far as I can see the method you are using is checking network connectivity and not necessarily internet connectivity. I would assume if you are on a network of any sort this would return true regardless of the internet being available or not? See this.

I have noticed that one way of checking for internet connectivity is as follows:

private bool IsInternetAvailable()
{
    try
    {
        Dns.GetHostEntry("www.google.com"); //using System.Net;
        return true;
    } catch (SocketException ex) {
        return false;
    }
}

The above code can be found (in VB.Net by reading the comment from Joacim Andersson [MVP]) in the following post.

Note: The latest edit was suggested by AceInfinity but was rejected in community review. My reputation is too low to override this so I made the change myself.

like image 12
Clarice Bouwer Avatar answered Oct 23 '22 04:10

Clarice Bouwer


Note that we are using the Windows.Networking.Connectivity.NetworkInformation and not the System.Net.NetworkInformation namespace.

public bool checkInternetAccess()
{
    var connectivityLevel = Windows.Networking.Connectivity.NetworkInformation
                           .GetInternetConnectionProfile().GetNetworkConnectivityLevel();

    return connectivityLevel == NetworkConnectivityLevel.InternetAccess;
}

Basically what ventura8 said. I would comment his solution, mentioning the namespaces, but I lack enough reputation.

like image 4
humHann Avatar answered Oct 23 '22 02:10

humHann