Check Internet Connection c#

This example will describe how to check Internet connection in asp.net using c sharp language. During code we mostly check if user is connected with remote server or not.

To check user internet connectivity we will send a request to a remote server. If remote server responde us it means that we are connected with Internet otherwise we are not connected with Internet. We can use this code with in thread (Background process) or without thread.

Follow the example code to check if user is connected with Internet or not.

protected bool IsInternetAvailable()
{
	System.Net.WebClient workstation = new System.Net.WebClient();
	byte[] data = null;

	try
	{
		data = workstation.DownloadData("http://www.google.com");// use any address to check connection.
		if (data != null && data.Length > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	catch
	{
		return false;
	}

}

Following code is calling above function to check Internet availability:

bool isNetworkAvailable = IsInternetAvailable();
if(isNetworkAvailable)
{
// yes Internet is available.
}
else
{
// No Internet is not available.
}

 

 

Leave a comment

Your email address will not be published. Required fields are marked *