Thursday, January 29, 2009

[VC++] Programmatically checking internet connection is active

You might have thought of how to check your internet connection in your program, here is how to check for internet connection programmatically. Following are the two functions of interest,
InternetGetConnectedState()
InternetCheckConnection ()

InternetGetConnectedState()
This function Retrieves the connected state of the local system. It Returns TRUE if there is an active modem or a LAN Internet connection. Below code snippet explains how to use the function.
DWORD dwFlags = 0;
if( InternetGetConnectedState ( &dwFlags, 0 ))
{
if( dwFlags & INTERNET_CONNECTION_OFFLINE )
{
// Connected but in offline mode
}
else
{
// Connection is active
}
}
else
{
// No connection
}

InternetCheckConnection()
InternetGetConnectedState() indicates that at least one connection to the Internet is available. It does not guarantee that a connection to a specific host can be established and InternetCheckConnection() function can be called to check if a connection to a specific destination can be established. Below code snippet may explain you the same.
if( InternetCheckConnection( "http://www.google.com", FLAG_ICC_FORCE_CONNECTION, 0 ))
{
// Connection to specified host exist
}
else
{
// Connection to specified host does not exist
}

No comments: