Detecting Internet Connections from Your C# or VB.NET Programs

Introduction

Knowing whether or not the PC running your application is connected to the internet or not, is essential for future application updates. This article will demonstrate four different and very easy ways to determine an internet connection.

Design

Our design is very simple. Open Visual Studio 2010 and start a VB.NET or a C# Windows Forms application. Then, simply add four buttons to your form. Name your buttons whatever you like; but keep in mind that for the coding samples, I have named my buttons btnMethod1, btnMethod2, btnMethod3 and btnMethod4.

Coding

As you can probably tell, we will use four different techniques to determine a valid internet connection. Why always settle for one method? :) Anyway, some methods will work faster than others, so you could use this article as a comparison of the various methods, if you'd like.

Enough blabbing, let us start!

The Namespaces

As usual, I'll start with the Namespaces necessary. It is probably just a force of habit, or I am way too organized, or I have OCD, I don't know. Add the following Imports / Usings to your VB.NET or C# program :

VB.NET

Imports System.Runtime
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Imports System.Net 'IPHostEntry, HttpWebRequest & HttpWebResponse in Method 4 & 2
Imports System.Net.Sockets 'TCP Client in Method 3

C#

using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Net; //IPHostEntry, HttpWebRequest & HttpWebResponse Method in 4 & 2
using System.Net.Sockets; //TCP Client in Method 3

The APIs

Next, we should add the API declarations. Add it just underneath your Class declaration :

VB.NET

 'Used in Method 1
'Retrieves the connected state of the local system
<DllImport("wininet.dll")> _
Private Shared Function InternetGetConnectedState(ByRef Description As Integer, ByVal ReservedValue As Integer) As Boolean
End Function

C#

 //Used in Method 1
//Retrieves the connected state of the local system
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

The Methods

Method 1

Add the following function:

VB.NET

 Public Shared Function Method1() As Boolean 'First and fastest way to determine Internet Connection
Try
Dim ConnDesc As Integer 'Return value

Return InternetGetConnectedState(ConnDesc, 0) 'Return result
MessageBox.Show("Connected")
Catch
Return False 'Not connected
End Try

End Function

C#

 public static bool Method1() //First and fastest way to determine Internet Connection
{
try
{
int ConnDesc; //Return value
MessageBox.Show("Connected");
return InternetGetConnectedState(out ConnDesc, 0); //Return result
}
catch
{
return false; //Not connected
}

}

What we did here was to make use of the InternetGetConnectedState API to determine an internet connection. We declared a variable named ConnDesc, which will hold the return value from the API. If there is a valid return value, the function will return True. If not, the function will return False

Method 2

Add the next function:

VB.NET

 Private Function Method2() As Boolean 'Second way, bit slower
Try
Dim iheObj As IPHostEntry = Dns.GetHostByName("www.codeguru.com") 'Gets the DNS information for the specified DNS host name
MessageBox.Show("Connected")

Return True
Catch
Return False 'Not connected
End Try
End Function

C#

 private bool Method2() //Second way, bit slower
{
try
{
IPHostEntry iheObj = Dns.GetHostByName("www.codeguru.com"); //Gets the DNS information for the specified DNS host name
MessageBox.Show("Connected");
return true;

}
catch
{
return false; // Not connected
}
}

With Method 2, we determine if a site domain does have a host. If the particular site does have a host, or rather, if this code is able to establish a host of a certain site, then obviously there must be an internet connection.

Method 3

Add the next function:

VB.NET

 Private Function Method3() As Boolean 'Third way, slightly slower than Method 1
Try
Dim tcpClient As New TcpClient("www.codeguru.com", 80) 'Provides client connections for TCP network services
tcpClient.Close()
MessageBox.Show("Connected")
Return True

Catch ex As System.Exception
Return False 'Not connected
End Try
End Function

C#

 private bool Method3() //Third way, slightly slower than Method 1
{
try
{
TcpClient tcpClient = new TcpClient("www.codeguru.com", 80); //Provides client connections for TCP network services
tcpClient.Close();
MessageBox.Show("Connected");
return true;
}

catch (System.Exception ex)
{
return false; //Not connected
}
}

In Method 3, we make use of a TcpClient, which checks the client connections on the computer. If it is able to obtain a website, it is valid.

Method 4

Add the final method:

VB.NET

 Public Shared Function Method4(ByVal url As String) As Boolean 'Fourth way, slowest
Dim hwrRequest As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 'Makes a request to a Uniform Resource Identifier (URI)
hwrRequest.Method = "HEAD" 'Read if there is a Head section
Try
Dim hwrResponse As HttpWebResponse = DirectCast(hwrRequest.GetResponse(), HttpWebResponse) 'Provides a response from a Uniform Resource Identifier (URI)
hwrResponse.Close()
MessageBox.Show("Connected")
Return True
Catch
Return False
End Try
End Function

C#

 public static bool Method4(string url) //Fourth way, slowest
{
HttpWebRequest hwrRequest = (HttpWebRequest) //Makes a request to a Uniform Resource Identifier (URI)
WebRequest.Create(url);
hwrRequest.Method = "HEAD"; //Read if there is a Head section
try
{
HttpWebResponse hwrResponse = (HttpWebResponse)hwrRequest.GetResponse(); //Provides a response from a Uniform Resource Identifier (URI)
hwrResponse.Close();
MessageBox.Show("Connected");
return true;
}
catch
{
return false;
}
} 

In our final function, we create an HttpWebRequest object, and then read the Head HTML section of the webpage that loaded. Based on this, it provides us with a response.

All that is needed now is to call these functions from our buttons. Add the Button events now:

VB.NET

 Private Sub btnMethod1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMethod1.Click
'Method 1
Method1()
End Sub

Private Sub btnMethod2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMethod2.Click
'Method 2
Method2()
End Sub

Private Sub btnMethod3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMethod3.Click
'Method 3
Method3()
End Sub

Private Sub btnMethod4_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMethod4.Click
'Method 4
Method4("http://www.Codeguru.com")
End Sub

C#

 private void btnMethod1_Click(object sender, EventArgs e)
{
//Method 1
Method1();
}

private void btnMethod2_Click(object sender, EventArgs e)
{
//Method 2
Method2();
}

private void btnMethod3_Click(object sender, EventArgs e)
{
//Method 3
Method3();
}

private void btnMethod4_Click(object sender, EventArgs e)
{
//Method 4
Method4("http://www.Codeguru.com");
}

I am including samples in VB.NET as well as C# with this article, in case you have missed a step or two.

Conclusion

There are probably more methods, or better methods to determine internet connections, but this article will act as a good resource to you if you ever need to do it. I hope you have enjoyed my article. Until next time! Cheers!

About the Author:

Hannes du Preez is a Microsoft MVP for Visual Basic for the fifth year in a row. He is a trainer at a South African-based company providing IT training in the Vaal Triangle. You could reach him at hannes [at] ncc-cla [dot] com



Related Articles

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: September 10, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild". This loop of continuous delivery and continuous feedback is …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds