Checking for a valid Internet connection

posted @ Saturday, October 9, 2004 5:00 PM

 

This is just my temporary solution as I have been busy doing other things at the moment.

#include "stdafx.h"

bool IsConnected();

LPCTSTR url = "http://www.google.com";
HINTERNET hINet, hResource;

int main(int argc, char* argv[])

    if(argc == 2)
    {
        if(strcmp(argv[1], "/?") == 0)
        {
            printf("Help (Input format):\n\n\"Http Application\" URL(optional)\n\n");
            return 0;
        }
        else
        {
            if(strstr(_strlwr(argv[1]), "http://") > 0)
                url = argv[1];
        }
    }

    HANDLE hWnd = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTitle(url);
    SetConsoleTextAttribute(hWnd, FOREGROUND_GREEN | FOREGROUND_INTENSITY);

    while(true)
    {
        if(IsConnected())
            printf("Connection exists.\n");
        else
            printf("Connection terminated.\n");
        Sleep(2000);
    }

    return 0;
}

bool IsConnected()
{
    bool bStatus = false;
 
    hINet = InternetOpen("Connection", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if(hINet == NULL)
        bStatus = false;

    hResource = InternetOpenUrl(hINet, url, NULL, 0, 
                        INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE, 0);
    if(hResource != NULL)
    {
        char buffer[1024];
        DWORD dwRead = {0};
  
        if(InternetReadFile(hResource, buffer, sizeof(buffer)-1, &dwRead))
        {
            bStatus = true;
        }
        else
        {
            bStatus = false;
        }
    }
    else
    {
        bStatus = false;
    }

    if(hINet)
    {
        InternetCloseHandle(hINet);
        hINet = NULL;
    }
    if(hResource)
    {
        InternetCloseHandle(hResource); 
        hResource = NULL;
    }
    return bStatus;
}