tags:

views:

214

answers:

4

What is the most fastest and most efficient way to check for an internet connection.

+2  A: 

Something like this should work.

System.Net.WebClient

public static bool CheckForInternetConnection()
{
    try
    {
        using (var client = new System.Net.WebClient())
        {
            client.DownloadString(new Uri("http://www.google.com"));
            return true;
        }
    }
    catch
    {
        return false;
    }
}
ChaosPandion
I'd suggest forward slashes instead of backslashes...
Jon Skeet
Just as I fix it. :)
ChaosPandion
You took the words right out of my mouth :)
Skilldrick
This is probably better than pinging Google, because I think we have no guarantee that Google continues to respond to pings. On the other hand, I cannot image a world where www.google.com does not return some HTML :)
Daniel Vassallo
@Daniel: true on the one hand, but on the other hand, actually downloading the website is a little overhead imo
Mef
4KB is not very much overhead.
ChaosPandion
+2  A: 

There is absolutely no way you can reliably check if there is an internet connection or not (I assume you mean access to the internet).

You can, however, request resources that are virtually never offline, like pinging google.com or something similar. I think this would be efficient.

Ping myPing = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success {
  // presumably online
}
Mef
A: 
public static bool HasConnection()
{
    try
    {
        System.Net.IPHostEntry i = System.Net.Dns.GetHostEntry("www.google.com");
        return true;
    }
    catch
    {
        return false;
    }
}

That works

slayerIQ
If you have google's IP in your DNS cache, it won't send a DNS request, so it could return true even if you're not connected
Thomas Levesque
A: 

Instead of checking, just perform the action (web request, mail, ftp, etc.) and be prepared for the request to fail, which you have to do anyway, even if your check was successful.

Consider the following:

1 - check, and it is OK
2 - start to perform action 
3 - network goes down
4 - action fails
5 - lot of good your check did

If the network is down your action will fail just as rapidly as a ping, etc.

1 - start to perform action
2 - if the net is down(or goes down) the action will fail
dbasnett