c++pingconnectivitywininetnic

Checking internet connection from C++ code


While working with large codebase for legacy applications, whenever I have seen a piece of code that checks whether an internet connection is active or not, I have mostly seen the uses of functions such as:

InternetCheckConnection(L"http://www.google.com",FLAG_ICC_FORCE_CONNECTION,0)
//or
BOOL bConnected = IsNetworkAlive(&dwSens)
//or
InternetGetConnectedState(&dwReturnedFlag, 0)
//or some other functions

but there exists a very very simple way to do this where you wouldn't need to include other header files of write code, that is:

if (system("ping www.google.com"))

My question is that what are the drawbacks, if any, to use ping from the code when I need to see if a connection is available or not?

Assuming that ping is not going to be disabled on the machines where my software is going to run.


Solution

  • The drawback with system("ping www.google.com") is twofold:

    1. If someone replaced the system ping command with their own, it could give you the wrong results [and if the process calling ping is running with extra privileges, it could do something "interesting" with that privilege]. This is generic for any system operation.

    2. You are starting another process, which then has to run and shut down before you get the answer [and of course do more or less the same things that InternetCheckConnection does - look up the name, translate it to an IP address, send packet to that address, wait for a response, interpret that response, and so on].