BOOL IsInternetConnected()

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

Alot of times, programming internet applications you need to know wether the computer is connected to the internet?

In some occasions you can try to use RasEnumConnections, in most cases on a typical computer opened Ras Connection mean that the user is connected to the internet. However, this idea won't work in case the user is connected to internet not via Ras device or is connected to some kind of local network.

We try to use common sence here. Since internet is something abstract, lets decide that user which is connected to internet, is the one who can connect to www.microsoft.com.

First I wanted to use ping, but found a lot of troubles with it. Therefore, I have decided to use sockets "directly". I didn't want to write some fance code here, rather I have wrote a simple function you can cut & paste into your application.

Another problem adressed in the function that in some computer a try to establish internet connection will bring dialup dialog. The function solve it by temporary disabling the feature in the registry and enabling it back afterwards.

Pay attention to the comments.


BOOL YourClassHere::IsInternetConnected (void)
{
 int nCheck = AfxSocketInit();
 CSocket m_Server;
 HKEY hKey;
 DWORD dwDial, dwDialType = REG_DWORD, dwDialSize = 4;
 DWORD dwNew = 0;
 BOOL bResult = true;
 
 if ( RegOpenKeyEx ( HKEY_CURRENT_USER,
    Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
     0, KEY_SET_VALUE, &hKey) != ERROR_SUCCESS)
    ; // We cannot find the key. Handle this situation or just continue
                                                
 if ( RegQueryValueEx( hKey, "EnableAutodial", NULL, &dwDialType,
  (BYTE *) &dwDial, &dwDialSize ) != ERROR_SUCCESS )
  ; // We cannot find the value. Handle it.

 if ( dwDial ) { // We need to change the value, in order to make
            // a dialup window not to show up.
  
  if ( (nCheck = RegSetValueEx( hKey, "EnableAutodial", NULL,
   dwDialType, (BYTE *) &dwNew, dwDialSize )) != ERROR_SUCCESS)
  ; // Failed? We shouldn't get here. You decide how to handle it
 }
  
 
 if ( !m_Server.Create() ) {                                                       
        // m_sError = _T( "Unable to create the socket." );
        bResult = false;
 }   

// You can use www.microsoft.com in order to check whether DNS is available
// or numeric IP otherwise 
 else if ( !m_Server.Connect( "www.microsoft.com", 80 ) ) {     //  207.46.130.150
        //m_sError = _T( "Unable to connect to server" );        
        m_Server.Close();
        bResult = false;
 }
 
 
 if ( dwDial ) {
  if ( (nCheck = RegSetValueEx( hKey, "EnableAutodial", NULL,
   dwDialType, (BYTE *) &dwDial, dwDialSize )) != ERROR_SUCCESS)
  ; // Failed? We shouldn't get it. You decide how to handle this.
 }
 
 RegCloseKey( hKey );
 return ( bResult );
}

I would like to thank Martin Tschepe for pointing me out this registry key.

Download source - 2KB

History



Comments

  • An easier alternative

    Posted by Legacy on 08/11/2003 12:00am

    Originally posted by: Patrick Philippot

    Hi,
    
    

    Edwin Eefting made a clever comment about using the IP
    routing table to detect a connection. I have implemented
    this brillant idea and I have to say that this is actually
    a very interesting solution.

    Basically, you just look at the system IP routing table and
    check whether an entry exists for a default gateway
    (0.0.0.0). If yes, the system either has an active dial-up
    connection or is connected via LAN, DSL or cable. As soon
    as the dial-up connection is broken, the default gateway
    entry disappears from the IP routing table.

    This doesn't guarantee that any request will succeed (the
    cable may be unplugged or the user may have logged off from
    the ISP) but you can check this afterwards, **the main
    interest of this approach being that is doesn't trigger any
    autodial process**. If the function below returns FALSE,
    you will not even try to access the Internet: you know that
    any request will fail anyway. If it returns TRUE, you can
    safely make a connection attempt without incurring the risk
    of triggering an autodial. You will possibly get an error
    when using WinInet or any socket function.

    Here's a sample routine:

    #include <iphlpapi.h>
    ...

    BOOL YourClass::CheckConnection()
    {
    MIB_IPFORWARDTABLE* pft;
    DWORD dwTableSize = 0;
    BOOL bHasDefaultRoute = FALSE;

    GetIpForwardTable(NULL, &dwTableSize, FALSE);
    pft = (MIB_IPFORWARDTABLE*) new BYTE[dwTableSize];

    if (GetIpForwardTable(pft,
    &dwTableSize,
    TRUE) == NO_ERROR)
    {
    for (unsigned int nIndex = 0;
    nIndex < pft->dwNumEntries;
    nIndex++)
    {
    if (pft->table[nIndex].dwForwardDest == 0)
    // Default route to gateway
    {
    bHasDefaultRoute = TRUE;
    break;
    }
    }
    }

    delete pft;

    return bHasDefaultRoute;
    }

    Note that your system must support the IPHLPAPI, which is
    not the case for Win95 and Windows NT 4 pre-SP4.

    This code has been tested on various configurations from
    Win98 to XP) and it worked fine each time.

    Hope this helps.

    --Patrick Philippot
    Microsoft MVP [.Net]
    Consulting Services
    www.mainsoft.fr

    • Absolutely Brilliant

      Posted by bob16972 on 03/26/2005 06:19pm

      Your solution should have been included in "Visual C++ Goodies" instead of "Function To Verify if Connected to the internet" methinks. Too bad the book came out first. Thanks Patrick (and Edwin) for sharing it

      Reply
    • Thanks

      Posted by skjacob on 02/11/2005 01:06am

      Ur solution works perfectly

      Reply
    Reply
  • Winsock Proxy handling

    Posted by Legacy on 01/20/2003 12:00am

    Originally posted by: Eugene Polonsky

    Using Winsock to check connection status--has anyone run into any issues regarding proxy server settings when attempting to verify connection?

    Reply
  • Error Message when use the function "InetIsOffline"

    Posted by Legacy on 04/02/2002 12:00am

    Originally posted by: Maverick

    Dear all:
    
    

    I need some one can help to slove this problem .
    "error LNK2001 :unresolved external symble __imp__InetIsOffline@4"

    I add one code "#include <intshcut.h> but my program still
    can not link with VC ++ 6.0.

    thanks the guy that can help me.

    • Reply for Error Message when use the function "InetIsOffline"

      Posted by skjacob on 02/11/2005 12:59am

      Add url.lib to ur settings\Link tab

      Reply
    Reply
  • Error in WININET.H

    Posted by Legacy on 12/27/2001 12:00am

    Originally posted by: Rey

    When I compile wininet.h I get an error with LPVOID, can anyone help?

    Reply
  • detecting internet status in VJ++

    Posted by Legacy on 11/13/2001 12:00am

    Originally posted by: Priyanka

    Hey, 
    
    

    I saw all the methods that u guys had suggested for finding out there is an active internet connection but wanted to know if anything similar is available in VJ++.

    Any help would be appreciated!!

    thnx,

    Priyanka

    Reply
  • Windows ME?

    Posted by Legacy on 09/30/2001 12:00am

    Originally posted by: Phil Hord

    I've heard from a user that autodial is erroneously triggered on Windows ME. Does anyone have any info on WinME registry settings to disable AutoDial?

    Reply
  • No existe el archivo

    Posted by Legacy on 08/08/2001 12:00am

    Originally posted by: V�ctor Lema

    no 'ta el archivo .zip

    Reply
  • Fix for the long delay

    Posted by Legacy on 07/24/2001 12:00am

    Originally posted by: Rob Adamson

    There seems to be a problem in the gethostbyname because I could not find a way to shorten the connection timeout.  30 seconds or more is way too long for most users.  I finally resorted to threads to make this work with a 5 second timeout.
    
    

    DWORD WINAPI ConnectThreadProc(LPVOID lpResult)
    {
    BOOL* lpbResult = (BOOL*) lpResult;

    *lpbResult = IsInternetConnected();
    return 0;
    }

    BOOL mfIsInternetConnected()
    {
    BOOL bResult = FALSE;
    DWORD dwThreadId = 0;

    BOOL bInternetConnected = FALSE;
    HANDLE hConThread = CreateThread(NULL, 0, ConnectThreadProc, &bInternetConnected, 0, &dwThreadId);

    if (WaitForSingleObject(hConThread, 5000) == WAIT_TIMEOUT)
    {
    TerminateThread(hConThread, 0);
    }
    return (bInternetConnected);
    }

    Reply
  • InternetGetConnectedState() API

    Posted by Legacy on 04/10/2001 12:00am

    Originally posted by: mike

    try using this from wininet.h/.lib
    
    working with ie4.0+

    BOOL InternetGetConnectedState(
    OUT LPDWORD lpdwFlags,
    IN DWORD dwReserved
    );

    Reply
  • A diamond in the rough!

    Posted by Legacy on 02/19/2001 12:00am

    Originally posted by: Bruce

         Let me start by saying that Ran is one smart cookie!  I am a very serious researcher, and I have investigated internet connection functions.  Ran provides the foundation for numerous possible utilitarian functions.  The genius behind IsInternetConnected() is the temporary alteration of EnableAutodial registry setting.  After altering this registry setting, you can perform numerous internet tasks without the fear of a Internet Connection dialog popping up.  I have altered Ran's function to exclude registry function error checking and I have also exchanged CSocket for CInternetSession, with an inclusion of CInternetException to catch any errors.
    
    My version of Ran's function is triggered by a 300000 millisecond timer (approx. 5 min.) which upon triggering checks for an internet connection. If a connection is established, it reads a string from an internet file and replaces an existing member variable string. I am not to keen on the CSocket class, but CInternetSession has many possibilities.
    Between Ran's original function and my alteration to CInternetSession, you folks should have a hay day. Please post useful alterations so that others may use them. Remember to use CInternetException to catch the errors.

    void CHDTripsterDlg::IsInternetConnected()
    {
    CStdioFile* pInfo;
    CInternetSession pInetSess;
    CString strNew;
    HKEY hKey;
    DWORD dwDial, dwDialType = REG_DWORD, dwDialSize = 4;
    DWORD dwNew = 0;

    RegOpenKeyEx(HKEY_CURRENT_USER,
    "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
    0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hKey);

    RegQueryValueEx(hKey, "EnableAutodial", NULL, &dwDialType,
    (BYTE *) &dwDial, &dwDialSize );

    RegSetValueEx( hKey, "EnableAutodial", NULL,
    dwDialType, (BYTE *) &dwNew, dwDialSize );
    try
    {

    pInfo = pInetSess.OpenURL("http://www.geocities.com/idbruce/bear.txt";);

    if(pInfo)
    {
    while(pInfo->ReadString(strNew))
    {
    if((lstrlen(strNew) > 0)&&
    (lstrcmp(strNew, strOld) != 0))
    {
    strOld = strNew;
    m_ctrlControl.SetText(strOld);
    }
    }
    }
    }

    catch (CInternetException* pEx)
    {
    //catch WinInet errors
    }

    pInetSess.Close();

    RegSetValueEx( hKey, "EnableAutodial", NULL,
    dwDialType, (BYTE *) &dwDial, dwDialSize);
    RegCloseKey(hKey);
    }

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date