DotNetLogo

We have many ways to verify if the user is connected to the internet, anyway, this native method can do it ‘on the way’ manually trying to connect to a website.

        /*

         * IsConnectedToInternet C# property by Michel Oliveira.
         * 2013/05/14
         * www.joshcellsoftwares.com

         You may need to use these libraries on your project:
         
         System.Net;
         
         GPL License.

         */
        public static bool IsConnectedToInternet
        {
            get
            {
                try //Try to do the web request.
                {
                    HttpWebRequest hwebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com"); //Do the request to the Microsoft website (can be anyone, it need to be online).
                    hwebRequest.Timeout = 10000; //10 seconds timeout to process the request.
                    HttpWebResponse hWebResponse = (HttpWebResponse)hwebRequest.GetResponse(); //Process the request.
                    if (hWebResponse.StatusCode == HttpStatusCode.OK) //Get the response.
                    {
                        return true; //If true, the user is connected to the internet.
                    }
                    else return false; //Else it is not.
                }
                catch { return false; } //If any problem occurs inside the method, stop and return false.
            }
        }
'
'
'         * IsConnectedToInternet VB.NET property by Michel Oliveira.
'         * 2013/05/14
'         * www.joshcellsoftwares.com
'
'         You may need to use these libraries on your project:
'         
'         System.Net;
'         
'         GPL License.
'
'         

Public Shared ReadOnly Property IsConnectedToInternet() As Boolean
	Get
		Try
			'Try to do the web request.
			Dim hwebRequest As HttpWebRequest = DirectCast(WebRequest.Create("http://www.microsoft.com"), HttpWebRequest)
			'Do the request to the Microsoft website (can be anyone, it need to be online).
			hwebRequest.Timeout = 10000
			'10 seconds timeout to process the request.
			Dim hWebResponse As HttpWebResponse = DirectCast(hwebRequest.GetResponse(), HttpWebResponse)
			'Process the request.
			If hWebResponse.StatusCode = HttpStatusCode.OK Then
				'Get the response.
					'If true, the user is connected to the internet.
				Return True
			Else
				Return False
				'Else it is not.
			End If
		Catch
			Return False
			'If any problem occurs inside the method, stop and return false.
		End Try
	End Get
End Property

Examples:

        if (IsConnectedToInternet)
        {
            Console.WriteLine("You are online!");
        }
        else Console.WriteLine("You are offline.");
If IsConnectedToInternet Then
	Console.WriteLine("You are online!")
Else
	Console.WriteLine("You are offline.")
End If

Good Luck,

Michel Oliveira – Software Engineer and Startup founder at joshcellsoftwares.com.