Checking For An Internet Connection

Wednesday Nov 26th 2003 by Karl Moore
Share:

Learn the best method for checking for an internet connection from a Visual Basic application.

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

About the Author

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

# # #

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved