Is an Internet Connection Available?

Checking whether an Internet connection is available isn’t always as easy as it sounds.
Admittedly, there is a Windows API call that can check whether a connection exists, but it’s extremely fragile and returns incorrect results if the machine has never had Internet Explorer configured correctly. Oops.

The best method is to actually make a Web request and see whether it works. If it does, you’ve got your connection. The following neat code snippet does exactly that. Just call IsConnectionAvailable and check the return value:

Public Function IsConnectionAvailable() As Boolean
    ' Returns True if connection is available
    ' Replace with a site that
    ' is guaranteed to be online - perhaps your
    ' corporate site, or
    Dim objUrl As New System.Uri("")
    ' Setup WebRequest
    Dim objWebReq As System.Net.WebRequest
    objWebReq = System.Net.WebRequest.Create(objUrl)
    Dim objResp As System.Net.WebResponse
        ' Attempt to get response and return True
        objResp = objWebReq.GetResponse
        objWebReq = Nothing
        Return True
    Catch ex As Exception
        ' Error, exit and return False
        objWebReq = Nothing
        Return False
    End Try

Here’s how you might use this function in your application:

If IsConnectionAvailable() = True Then
    MessageBox.Show("You are online!")
End If

You might also like...


Karl Moore


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debuggers don't remove bugs. They only show them in slow motion.”