Check Internet Connection in C++

Welcome back! In this tutorial, we will learn how to check the status of the internet connection of your system in C++.

Internet is a necessity in the modern world. We live in a world of connected devices, be it our laptops or the IoT products in our homes such as Alexa. It is of utmost importance for us to stay connected and we can check that out in C++ as well.

Checking Internet Connection in C++

We can check the status of our internet connection with the InternetCheckConnectionA function included in the “wininet” library in C++. If you are working on an application, this function will allow you to check its connectivity status and rectify anything which might go wrong before you release your application amongst the audience.

Syntax for the function

The function takes in three arguments:

  1. lpszUrl –  a pointer to a string that is null terminated and specifies the URL used for testing.
  2. dwFlags – FLAG_ICC_FORCE_CONNECTION is used as a flag here to set the connection.
  3. dwReserved – A reserved parameter assigned to 0.
bool InternetConnectionA(lpszUrl, dwFlags, dwReserved);

Let us now look at a small, sample code to verify whether our system is connected to the internet or not

#include <iostream>
#include<windows.h>
#include<psapi.h>
using namespace std;
#include <wininet.h>
#pragma comment(lib, "Wininet.lib")
int main()
{
        char url[256];
        strcat(url, "http://170.187.134.184");
        bool isconnect = InternetCheckConnectionA(url, FLAG_ICC_FORCE_CONNECTION,0);
        if(isconnect)
        {
                cout<<"\nInternet Connected";
        }
        else
        {
                cout<<"\n Not connected!!";
        }
        return 0;
}

 

Output:
Internet Connected

Code Explanation

  • To check for internet connectivity in C++, the first step is to include necessary header files.
  • <windows.h> for declaring all the functions present in the windows API. We use it as we are checking the internet connection on a Windows machine.
  • <psapi.h> library makes it possible to attain information from the device driver regarding internet connectivity.
  • <wininet.h> is used for opening a FTP or HTTP session.
  • Once all header files have been contained in the program,  define a URL as a char array.
  • Concatenate the URL of choice with the char variable.
  • Define a bool variable isconnect and assign it to our InternetCheckConnectionA() function.
  • This returns either a true(or 1) if the internet is connected and stores that boolean result in isconnect variable.
  • Else it stores a false(or 0).
  • If isconnect is true, we print the statement Internet Connected
  • If we give the URL as undefined, or isconnect is false, the output would show Not connected!!

 

Leave a Reply

Your email address will not be published. Required fields are marked *