Checking for Internet Connection

In my previous post where I had shared about checking for Network Connectivity, NetworkInterface.GetIsNetworkAvailable(), however what the method is actually doing is to simple check for network connection and not necessary internet connection. There are situation where there is network connection but not internet connection and the method will still return a true.

A workabout to this issue is to “ping” a website that is almost always available, and one such example will be http://www.google.com
If it crashes when attempting to read http://www.google.com, it would clearly indicate that there is no internet connection.

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

I would suggest using NetworkInterface.GetIsNetworkAvailable() and the above method together to better improve on the efficient on the app because if the NetworkInterface.GetIsNetworkAvailable() return a false, there is no need to continue with the pinging of the website.

Advertisements
This entry was posted in C#, Windows Phone, winrt and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s