What is the most fastest and most efficient way to check for an internet connection.
+2
A:
Something like this should work.
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
2010-01-09 00:51:35
I'd suggest forward slashes instead of backslashes...
Jon Skeet
2010-01-09 00:53:12
Just as I fix it. :)
ChaosPandion
2010-01-09 00:53:35
You took the words right out of my mouth :)
Skilldrick
2010-01-09 00:54:08
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
2010-01-09 01:01:57
@Daniel: true on the one hand, but on the other hand, actually downloading the website is a little overhead imo
Mef
2010-01-09 01:05:13
4KB is not very much overhead.
ChaosPandion
2010-01-09 01:07:09
+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
2010-01-09 00:52:27
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
2010-01-09 01:05:09
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
2010-01-09 02:19:08
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
2010-01-31 15:29:08