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 www.yoursite.com with a site that
    ' is guaranteed to be online - perhaps your
    ' corporate site, or microsoft.com
    Dim objUrl As New System.Uri("http://www.yoursite.com/")
    ' Setup WebRequest
    Dim objWebReq As System.Net.WebRequest
    objWebReq = System.Net.WebRequest.Create(objUrl)
    Dim objResp As System.Net.WebResponse
    Try
        ' Attempt to get response and return True
        objResp = objWebReq.GetResponse
        objResp.Close()
        objWebReq = Nothing
        Return True
    Catch ex As Exception
        ' Error, exit and return False
        objResp.Close()
        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...

Comments

Karl Moore

Contribute

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.

“Owning a computer without programming is like having a kitchen and using only the microwave oven” - Charles Petzold