Saturday, May 22, 2010

How to Check Internet Connectivity using VBA

The following code snippet uses API functions to check Internet connectivity and also the type of connection
:
Public Declare Function InternetGetConnectedState _
                         Lib "wininet.dll" (lpdwFlags As Long, _
                                            ByVal dwReserved As Long) As Boolean

Private Declare Function InternetGetConnectedStateEx Lib "wininet.dll" Alias "InternetGetConnectedStateExA" ( _
ByRef lpdwFlags As Long, _
ByVal lpszConnectionName As String, _
ByVal dwNameLen As Long, _
ByVal dwReserved As Long) As Long


'Local system uses a modem to connect to the Internet.
Private Const INTERNET_CONNECTION_MODEM As Long = &H1

'Local system uses a LAN to connect to the Internet.
Private Const INTERNET_CONNECTION_LAN As Long = &H2

'Local system uses a proxy server to connect to the Internet.
Private Const INTERNET_CONNECTION_PROXY As Long = &H4

The following API functions are used

Function IsConnected() As Boolean
    
    Dim Stat As Long
    
    IsConnected = (InternetGetConnectedState(Stat, 0&) <> 0)
    
    If IsConnected And INTERNET_CONNECTION_LAN Then
        MsgBox "Lan Connection"
    ElseIf IsConnected And INTERNET_CONNECTION_MODEM Then
        MsgBox "Modem Connection"
    ElseIf IsConnected And INTERNET_CONNECTION_PROXY Then
        MsgBox "Proxy"
    End If
End Function

If you want to know just if it is connected or not you can use the following:

CBool(InternetGetConnectedStateEx(0, vbNullString, 512, 0&))

2 comments:

  1. excellent, worked instantly. Thanks for this.

    ReplyDelete
  2. It sure doesn't work for me. If I go outside and disconnect the cable coming into my house, and then run this code it still thinks I'm connected. How do I tell for sure that I can actually reach the internet? Almost every answer I've been able to find assumed set if I can connect to my local wifi, that I'm connected to the internet. I need to know if I can really surf the web. Anyone know how to do this?

    ReplyDelete

StumbleUpon
Share on Facebook
Related Posts Plugin for WordPress, Blogger...
Download Windows Live Toolbar and personalize your Web experience! Add custom buttons to get the information you care about most.