Microsoft & .NETVisual BasicChecking For An Internet Connection

Checking For An Internet Connection

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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.

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories