Checking for internet connectivity

This is a technique I’ve used in the past to check for internet connectivity and it has never really failed to work for me. But I won’t say it’s a 100% safe method and you’ll have to verify that this works for your target environment before putting it into use.

BOOL CheckInternetConnection(LPCTSTR szURL)
    DWORD flags = 0;
    if( InternetGetConnectedState( &flags, 0 ) )
        if( InternetCheckConnection( szURL,
            FLAG_ICC_FORCE_CONNECTION, 0 ) )
            return TRUE;
            return FALSE;
        return FALSE;

And you can put the function to use as follows :-

if( CheckInternetConnection( "" )
   || CheckInternetConnection( "" )
   || CheckInternetConnection( "" ) )
    // We are online
    // We are offline

You can replace the three web-sites I’ve used with your custom URLs if you want to do so, I just chose those three as I think the chances that all 3 of them are down at the same time are quite low.


6 thoughts on “Checking for internet connectivity

  1. Just a thought, but wouldn’t it be a good idea to replace ands (&&) with ors (||) so if one or more site is down but at least one is up it will still consider the connection as live.

  2. Geez! I donno how I typed that! Thanks a lot Matt. I’ve corrected the error – I was typing code into the blog-text-box directly and wasn’t copy/pasting from Visual Studio. From now on, I’ll know better than to trust direct typing. 😀

  3. MS publised a KB at on this. The only InternetGetConnectedState() guarantees is “attempting your connection will NOT cause you to be prompted”. The KB suggests you ping your target (assuming it’s “pingable”) using IsDestinationReachable() in addition to checking for connected state.

    I tested Nick P’s program and it reported “No connection” immediately I disabled my LAN connection but continued reporting 60 “No connection”‘s after I reanabled it. That’s 120 seconds! Well, I guess I should be happy that it did realise I was reconnected, albeit a bit slow.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s