How to Check Internet Connection Availability Using Qt/C++

Posted on Posted in Qt Tutorials, Tutorials

The one and only correct answer is, you have to check if you can access some famous (like Google or Facebook) server on the internet. This question comes up a lot and surprisingly enough there is no clear answer for it because being connected to the internet can have different meanings in different countries. For example in my home country of Iran (and in China and some other countries too), Facebook and some other popular websites are forbidden under the law, so being connected to the Internet does not mean being connected to Facebook, and vice versa. So, you have to use a website which is not forbidden in the country your app is going to be used, and then use the simple approach below:

As you can see in the example code below, I simply have created a QNetworkAccessManager to send a request to Google, but be careful, even Google might be banned in some countries.

QNetworkAccessManager nam;
QNetworkRequest req(QUrl(““));
QNetworkReply *reply = nam.get(req);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
QMessageBox::information(this, “Info”, “You are connected to the internet :)”);
QMessageBox::critical(this, “Info”, “You are not connected to the internet :(“);

Don’t forget to add the following to your list of incudes:

#include <QtWidgets>
#include <QtNetwork>

Also you have to add network module to your Project .PRO file:

QT += network

This simple piece of code can be used in a function to tell you if you are connected to the internet or not. As you can see, Available Bytes will tell you your connection’s status.

Leave a Reply

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