Check if there is an active Internet connection

This is my first real post on “Visual Basic 6 Tips & Tricks” category 🙂

In many cases you need to check if the computer on which your VB6 application runs has an active Internet connection ( example : you have a small VB6 application that connects to a web server to retrieve the current weather ). To check this we need to use the InternetGetConnectedStateEx API function which will return 0 ( false ) if there is no connection or 1 ( true ) if there is an Internet connection.
The function itself is easy enough but if you have any questions feel free to ask 🙂

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

Public Function CheckInternetConnection() As Boolean
    Dim aux As String * 255
    Dim r As Long
    r = InternetGetConnectedStateEx(r, aux, 254, 0)
    If r = 1 Then
        CheckInternetConnection = True
    Else
        CheckInternetConnection = False
    End If
End Function

To use it just call it without any parameters, like below :

...
If (CheckInternetConnection = True)
    MsgBox "We have an active Internet connection!"
Else
    MsgBox "We don't have an active Internet connection!"
End If
...

That’s all 🙂

9 comments on “Check if there is an active Internet connection

  1. This code will always return true when we’re on LAN and connected internet to modem, whether connection active or not.
    Thx.

  2. The Internet Connection Test works great for me. Using VB6, how can I connect to a time server in order to automatically set my system clock. Is there any source code available to illustrate this? It would be so appreciated. I am a hobbyist with intermediate programming skills in VB6, but know nothing about .NET. I have several projects that I used to teach myself VB6 and want to expand them. Thanks. (Boyd Prestwood)

  3. When I connect peer-peer it still shows am connected to the internet yet there is no internet connection. I was just transferring data.

  4. this code suck !! always connected. it return false only if I unplug internbet cable from my computer, but i’m working on terminal server and this code is useless.

  5. This is the best VB 6.0 Code for checking internet status i’ve found over the internet. Thank you bro! The others ive found does’nt work for me. This one works straight.

  6. tHIS DOES NOT WORK UNLESS YOU STEP THROUGH THE PROGRAM STEP BY STEP IN DEBUG MODE

    sINCE THIS IS RATHER USELESS TO A USER, IT MAKES THE ABOVE CODE TOTALLY UNUSABLE

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.