'Reliable method to check internet connection in C++ application: gethostbyname() failing

I am developing a C++ network application on Windows. I need to check if internet connection is there or not. I am using gethostbyname(), but it is giving incorrect information when the system is connected through a proxy. InternetCheckConnection() and InternetGetConnectedState() are also not giving reliable results under different conditions. Is there a reliable way to check for internet connectivity covering all the conditions such as proxy and VPN?

Update:

In our company network WinHttpGetProxyForUrl() is failing with the error ERROR_WINHTTP_AUTODETECTION_FAILED and WinHttpSendrequest() is failing with error ERROR_WINHTTP_NAME_NOT_RESOLVED.

In open network WinHttpSendrequest() is successful.



Solution 1:[1]

Plain old way !

Include:

#include <wininet.h>
#pragma comment(lib,"Wininet.lib")

In your Method:

char url[128];
strcat(url, "http://www.techtoolbox.com");
bool bConnect = InternetCheckConnection(url, FLAG_ICC_FORCE_CONNECTION, 0);


if (bConnect)
{
    //internet connection exists !
}
else
{
            //internet DOES NOT connection exists !
}

Hope it helps.

Solution 2:[2]

The best way to test the availability of any resource is to try to use it. You only care about the Internet if there is something out there you want to connect to. So, try to connect to it, in the normal course of your program, and handle the errors. Don't try to second-guess what might happen if you try. First, you're trying to predict the future. Second, you aren't necessarily exercising the same things that the actual connection would exercise. Third, your test may succeed and your subsequent use fail due to an intervening condition changing. Fourth, you have to handle the errors from the real use of the resource anyway: why write all that code twice?

Solution 3:[3]

A simple solution is to try to connect to a well-known host, if it succeeds then you have a connection.

Solution 4:[4]

In my opinion a way is to create a socket and try connecting a known host. These links will help: For windows: http://msdn.microsoft.com/en-us/library/ms740673(VS.85).aspx and for unix http://www.tenouk.com/cnlinuxsockettutorials.html.

HTH
Anil

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user207421
Solution 3 Some programmer dude
Solution 4 anil