Check if Internet Connection is available.

There are different ways to check if the internet connection is available. Below are few simple ways to do it.

System.Net Namespace offers different classes to acheive that.

WebRequest, WebResponse, HttpWebRequest and HttpWebResponse classes can be used to call a website and get response back.

       /// <summary>
      /// Ping the specified URL.
      /// </summary>
      /// <param name="url">The URL.</param>
      /// <returns></returns>
      public static bool Ping(Uri url)
      {
         bool isInternetAvailable = false;
         try
         {
            WebRequest request = WebRequest.Create(url);
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
               if (response != null && response.StatusCode == HttpStatusCode.OK)
               {
                  response.Close();
                  isInternetAvailable = true;
               }
            }
         }
         catch
         {
            // Ignore the exception
         }

         return isInternetAvailable;
      }

      // Consume the ping method
      bool isInternetAvailable = Ping(new Uri("http://www.google.com/"));

In the above code, if internet or the url is not accessible, request.GetResponse() will throw an exception.

WebClient is another class that can be used to send and receive data from website or other resources accessed via a URI.

      /// <summary>
      /// Pings the specified URL.
      /// </summary>
      /// <param name="url">The URL.</param>
      /// <returns></returns>
      public static bool Ping(Uri url)
      {
         bool isInternetAvailable = false;
         try
         {
            using (WebClient client = new WebClient())
            {
               string response = client.DownloadString(url);
               isInternetAvailable = !string.IsNullOrEmpty(response);
            }
         }
         catch
         {
            // Ignore the exception
         }

         return isInternetAvailable;
      }

      // Consume the Ping method
      bool isInternetAvailable = Ping(new Uri("http://www.google.com"));

If internet or uri address is not available, “client.DownloadString(url)” will throw an exception. This method does not care how webpage behaves. Webpage may send error message and the ping method will still return positive.

We can take further step to get specific response by accessing a text file with certain keyword written like “Success”.

        private static bool Ping(uri url)
        {
            var isInternetAvailable = false;
            System.IO.StreamReader stream = null;

            try
            {
                var request = System.Net.WebRequest.Create(url);

                // Get the stream from the returned web response
                using (stream = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
                {
                	var response = stream.ReadLine();

                	canAccessWeb = !string.IsNullOrEmpty(response) && string.Equals(response, "SUCCESS", StringComparison.OrdinalIgnoreCase);
                }
            }
            catch
            {
                isInternetAvailable = false;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
            }

            return isInternetAvailable;
        }

        // Consume Ping Method
       bool isInternetAvailable = Ping(new Uri("http://www.mywebsite.com/TestConnection.txt"));

Above methods checks for resources available by URI.

NetworkInterface class, avalaible in System.Net.NetworkInformation Namespace, can be used to check if network connection is available. This could be any network including LAN.

      /// <summary>
      /// Determines whether [is internet available].
      /// </summary>
      /// <returns>
      ///   <c>true</c> if [is internet available]; otherwise, <c>false</c>.
      /// </returns>
      public static bool IsInternetAvailable()
      {
         bool isInternetAvailable = false;
         if(NetworkInterface.GetIsNetworkAvailable())
         {
            isInternetAvailable = true;
         }
         return isInternetAvailable;
      }

References:

System.Net: http://msdn.microsoft.com/en-us/library/btdf6a7e.aspx

System.Net.NetworkInformation: http://msdn.microsoft.com/en-us/library/3ew4thdx.aspx

Happy Coding…

 

Leave a Reply