0

Could this code snippet return false despite availability of internet connection ?

   private bool ConnectionIsOk()
    {
        try
        {
            using (var client = new WebClient())
            using (var stream = client.OpenRead("http://www.google.com"))
            {
                return true;
            }
        }
        catch
        {
            return false;
        }
    }

this part of code I use in my program , when my friend started my program he said that this function returned false despite availability of internet connection !! could this be true ? and when ?

Karam Najjar
  • 527
  • 5
  • 21

3 Answers3

3

There are numerous ways this could fail. It actually did for me too.

I am connecting to the internet via a proxy, so debugging through Visual Studio requires me to enter proxy-authentication details. Thus, running this code from a proxy could return false.

Another option could be where google is not available and doesn't return any response when opening.

Your DNS could also not be resolving the link to google you provided, which also makes the method return false. You could enter the IP-adress instead to bypass that possibility.

In the case of optimising your code, I would first keep the exception-details and return those. They could be usefull to the user of your method; the additional information could actually help them in figuring out why their internetconnection isn't functioning properly.

You could also try the pinging-method provided in this topic: What is the best way to check for Internet connectivity using .NET?

Community
  • 1
  • 1
Matthijs
  • 3,162
  • 4
  • 25
  • 46
2

Of course it can. If you can't reach Google for any reason, it will return false. If your DNS is down (but not your internet connection) it will return false. Referencing to a single hostname is not ideal.

  • so what is the ideal way to check for internet connection ? – Karam Najjar Aug 11 '14 at 08:48
  • That really depends on what you mean by "internet connection". The internet isn't a single, monolithic entity that you connect to, it's a network of networks. I think you need to think about why you want to check this. If you want to connect to a certain host, just try doing that. Otherwise, you'll have to define what it means to be "connected to the internet". You could arbitrarily define that to be connectivity to Google, or some other host, but ultimately there are innumerable hosts on the internet and you can't check all of them. – Robert Allan Hennigan Leahy Aug 11 '14 at 09:30
1

If an internet connection is available, but either:

  1. "www.google.com" cannot be resolved (through DNS)
  2. The connection to that server does not succeed (for whatever reason)

The function will return false.

So the answer to your question is "yes".