Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to check network status?



  • I want to check the status of the network to know if I can connect to the Internet.
    What should I do?

    I did as below:

    Utility.h

    class Utility: public QObject{
        Q_OBJECT
    public:
        static bool IsOnline();
    };
    

    Utility.cpp

    bool Utility::IsOnline()
    {
    
       bool result = false;
       QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
    
       for (int i = 0; i < ifaces.count(); i++)
       {
           QNetworkInterface iface = ifaces.at(i);
           if ( iface.flags().testFlag(QNetworkInterface::IsUp)
                && !iface.flags().testFlag(QNetworkInterface::IsLoopBack) )
           {
               // this loop is important
               for (int j=0; j<iface.addressEntries().count(); j++)
               {
                   // we have an interface that is up, and has an ip address
                   // therefore the link is present
    
                   // we will only enable this check on first positive,
                   // all later results are incorrect
                   if (result == false)
                       result = true;
               }
           }
       }
    
       return result;
    }
    

    If I disconnect the Ethernet connection from the Control Panel in Windows on VM, it returns false. -> It works.
    However, if I turn off the wifi of mac and enable Ethernet from Contro Panel in Windows on VM, it returns true. -> It should return false.

    What should I do?


  • Moderators

    Some platforms (Android) have a native API for this. A rock-solid (and quite wasteful) solution for all platforms is to ping a well-known server like Google (or your own server if you have one) periodically. If the connection does not work, you know that there is no Internet access.


Log in to reply