Sunday, February 01, 2004

I just finished assisting on  a project with a customer that was rolling out a really cool .NET based Pocket PC Phone application. One thing we found we needed was a quick way to check for an Internet connection. We originally, figured that we would just call the Web Service and if it failed we would know we didn’t have a connection. They had some business requirements that prevented this. Instead of that we decided that it would be easier and cleaner to do just do a quick test for connectivity.

 

Here is the general function we came up with:

 

Imports System.Net

 

Public Function GotInet() As Boolean

        Dim webrequest As HttpWebRequest

        Dim webresponse As HttpWebResponse

        Try

            webrequest = CType(webrequest.Create("http://mycompany.com"), HttpWebRequest)

            webresponse = CType(webrequest.GetResponse(), HttpWebResponse)

            webrequest.Abort()

 

            ' check the response to make sure that we got something

            If webresponse.StatusCode = HttpStatusCode.OK Then

                GotInet = True

            End If

 

            ' was there an error?

        Catch weberror As WebException

            GotInet = False

        Catch except As Exception

            GotInet = False

        End Try

 

    End Function

 

Not incredibly pretty but definitely functional. A return value of true would then trigger the firing of the Web Service call.


11:07:39 PM