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;
        else
            return FALSE;
    }
    else
        return FALSE;
}

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

if( CheckInternetConnection( "http://www.google.com" )
   || CheckInternetConnection( "http://www.microsoft.com" )
   || CheckInternetConnection( "http://www.yahoo.com" ) )
{
    // We are online
}
else
{
    // 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 http://support.microsoft.com/kb/242558 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 to Nish Cancel reply