A situation we had in a recent project (Windows Application) was to take some actions based on whether we had an Internet Connection or not. Though it sounds very simple, there is no straight forward way to determine this. This because you can be connected by numerous methods – Internet via LAN/Wireless or Modem/Dialup or thru’ IR/Bluetooth, etc.

Couple of years back, when we were building a Cricket Score Alert Application in VB 6.0, we used to download a very small file via HTTP, and if succeeded we concluded that the Internet Connection was present. This time, I wanted the solution in VB.NET and expected to find a better solution. After several Internet searches, I came across this article (KB Article: 821770), which talks about WinInet DLL. Though this WinInet function gives you good information on the type of Network Connection (LAN or Dialup, etc.), it doesn’t still say for sure you have an active Internet connection.

Instead of calling WinInet through Interop from VB.NET, I would have loved to see a native function in .NET Framework BCL – Framework folks, are you listening?.

You can download the code snippet here, for using the “InternetGetConnectedState” WinInet Function.

#Region "InternetAPIDeclaration"
    Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef lpdwFlags As Int32, _
    ByVal dwReserved As Int32) As Boolean

    Private Enum Flags As Integer
        'Local system uses a LAN to connect to the Internet.
        INTERNET_CONNECTION_LAN = &H2
        'Local system uses a modem to connect to the Internet.
        INTERNET_CONNECTION_MODEM = &H1
        'Local system uses a proxy server to connect to the Internet.
        INTERNET_CONNECTION_PROXY = &H4
        'Local system has RAS installed.
        INTERNET_RAS_INSTALLED = &H10
    End Enum
    Private Const ERROR_SUCCESS = &H0
    Private Const ERROR_INVALID_PARAMETER = &H87

    Private mlConnection As Int32
#End Region
  

    Private Function DetectConnectionType() As String
        Dim lngFlags As Long

        If InternetGetConnectedState(lngFlags, 0) Then
            'connected.
            If lngFlags And Flags.INTERNET_CONNECTION_LAN Then
                'LAN connection.
                Return ("LAN connection.")
            ElseIf lngFlags And Flags.INTERNET_CONNECTION_MODEM Then
                'Modem connection.
                Return ("Modem connection.")
            ElseIf lngFlags And Flags.INTERNET_CONNECTION_PROXY Then
                'Proxy connection.
                Return ("Proxy connection.")
            End If
        Else
            'not connected.
            Return ("Not connected.")
        End If
    End Function

Categorized in:

Tagged in: