Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to check whether the computer connects the internet?

How to check whether the computer connects the internet?

Scheduled Pinned Locked Moved Unsolved General and Desktop
30 Posts 14 Posters 16.1k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Q Offline
    Q Offline
    Qingshui Kong
    wrote on 18 Jan 2019, 09:16 last edited by
    #1

    Hello everybody,

    Could somebody give me some advice?

    I want to check whether the computer connects to the internet. And I find some answer on the internet. But they don't work well.

    1. Use QNetworkConfigurationManager::isOnline(). It doesn't work. Sometimes it returns true even if I disconnect the internet and doesn't receive any onlineStateChanged signal(on windows system). And sometimes it returns true even though I disconnect the internet and can receive some onlineStateChanged signal, and it often receive a disconnect signal before receive an online signal(on ubuntu system). So I think it doesn't work.

    2. Use QHostInfo::lookupHost(). It works! But if I disconnect the internet it returns online for several minutes, and if I connect the internet it returns online immediately. And if I use command (dig) on the terminal, it returns disconnect immediately after I disconnect the internet.
      Do I make some mistake?

    Could somebody give me some other solutions?

    I just want to check the internet state as soon as possible.

    Thank you in advance!

    K 1 Reply Last reply 10 Feb 2021, 12:31
    1
    • S Offline
      S Offline
      sierdzio
      Moderators
      wrote on 18 Jan 2019, 10:00 last edited by
      #2

      To clarify - you want to know if computer is connected to a network or Internet?

      Because QNetworkConfigurationManager::isOnline() will return true when connected to a network (LAN, WiFi etc.).

      I think the only reliable way of checking if there is Internet connectivity is to ping a server. If you get a reply from some server (either one you own or - that's a bit ugly - external one like google.com), then Internet is connected. If it times out - no Internet.

      On Android, there is an API for this - the system checks connectivity for you (it pings google.com).

      (Z(:^

      Q 1 Reply Last reply 18 Jan 2019, 11:16
      5
      • S sierdzio
        18 Jan 2019, 10:00

        To clarify - you want to know if computer is connected to a network or Internet?

        Because QNetworkConfigurationManager::isOnline() will return true when connected to a network (LAN, WiFi etc.).

        I think the only reliable way of checking if there is Internet connectivity is to ping a server. If you get a reply from some server (either one you own or - that's a bit ugly - external one like google.com), then Internet is connected. If it times out - no Internet.

        On Android, there is an API for this - the system checks connectivity for you (it pings google.com).

        Q Offline
        Q Offline
        Qingshui Kong
        wrote on 18 Jan 2019, 11:16 last edited by
        #3

        @sierdzio
        Thank you!
        Yes, I want to know if computer is connected to Internet.

        To ping a server is also a solution I find on the Internet. But I don't know how to check the result with QT. Maybe I should have a try first.

        W 1 Reply Last reply 17 Feb 2023, 23:02
        0
        • S Offline
          S Offline
          sierdzio
          Moderators
          wrote on 18 Jan 2019, 11:26 last edited by sierdzio
          #4

          See documentation for QNAM. The description there shows how to send a request and check it's status/ reply.

          (Z(:^

          Q 1 Reply Last reply 18 Jan 2019, 11:32
          4
          • S sierdzio
            18 Jan 2019, 11:26

            See documentation for QNAM. The description there shows how to send a request and check it's status/ reply.

            Q Offline
            Q Offline
            Qingshui Kong
            wrote on 18 Jan 2019, 11:32 last edited by
            #5

            @sierdzio
            OK, thank you!
            I will read it first.

            1 Reply Last reply
            0
            • F Offline
              F Offline
              fanxinglanyu
              wrote on 28 Jan 2021, 01:58 last edited by
              #6

              I use a method to solve this problem.This is my code:

              bool MainWindow::check()
              {
                  QTcpSocket* sock = new QTcpSocket(this);
                  sock->connectToHost("www.google.com", 80);
                  bool connected = sock->waitForConnected(30000);//ms
              
                  if (!connected)
                  {
                      sock->abort();
                      return false;
                  }
                  sock->close();
                  return true;
              }
              
              1 Reply Last reply
              2
              • E Offline
                E Offline
                euchkatzl
                wrote on 28 Jan 2021, 07:00 last edited by
                #7

                It is really no good idea to ping google for detecting a working internet connection.
                Your customers will have to verify that they are not a bot on every google search afterwards.

                I have done this depending on the platform in native code:

                Windows:

                bool ReachabilityCheck::internetAvailable()
                {
                    bool result = true;
                
                    DWORD lpresult;
                    BOOL winresult = InternetGetConnectedState(&lpresult,0);
                    result = winresult == 1 ? true : false;
                
                    return result;
                }
                

                macOS:

                bool ReachabilityCheck::internetAvailable()
                {
                    struct sockaddr_in zeroAddress;
                    bzero(&zeroAddress, sizeof(zeroAddress));
                    zeroAddress.sin_len = sizeof(zeroAddress);
                    zeroAddress.sin_family = AF_INET;
                
                    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
                    if (reachability != NULL) {
                        //NetworkStatus retVal = NotReachable;
                        SCNetworkReachabilityFlags flags;
                        if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
                            if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
                            {
                                // If target host is not reachable
                                return NO;
                            }
                
                            if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
                            {
                                // If target host is reachable and no connection is required
                                //  then we'll assume (for now) that your on Wi-Fi
                                return YES;
                            }
                
                
                            if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                                 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
                            {
                                // ... and the connection is on-demand (or on-traffic) if the
                                //     calling application is using the CFSocketStream or higher APIs.
                
                                if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                                {
                                    // ... and no [user] intervention is needed
                                    return YES;
                                }
                            }
                
                //            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
                //            {
                //                // ... but WWAN connections are OK if the calling application
                //                //     is using the CFNetwork (CFSocketStream?) APIs.
                //                return YES;
                //            }
                        }
                    }
                
                        return NO;
                  //  return result;
                }
                
                B H 4 Replies Last reply 28 Jan 2021, 07:20
                4
                • E euchkatzl
                  28 Jan 2021, 07:00

                  It is really no good idea to ping google for detecting a working internet connection.
                  Your customers will have to verify that they are not a bot on every google search afterwards.

                  I have done this depending on the platform in native code:

                  Windows:

                  bool ReachabilityCheck::internetAvailable()
                  {
                      bool result = true;
                  
                      DWORD lpresult;
                      BOOL winresult = InternetGetConnectedState(&lpresult,0);
                      result = winresult == 1 ? true : false;
                  
                      return result;
                  }
                  

                  macOS:

                  bool ReachabilityCheck::internetAvailable()
                  {
                      struct sockaddr_in zeroAddress;
                      bzero(&zeroAddress, sizeof(zeroAddress));
                      zeroAddress.sin_len = sizeof(zeroAddress);
                      zeroAddress.sin_family = AF_INET;
                  
                      SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
                      if (reachability != NULL) {
                          //NetworkStatus retVal = NotReachable;
                          SCNetworkReachabilityFlags flags;
                          if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
                              if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
                              {
                                  // If target host is not reachable
                                  return NO;
                              }
                  
                              if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
                              {
                                  // If target host is reachable and no connection is required
                                  //  then we'll assume (for now) that your on Wi-Fi
                                  return YES;
                              }
                  
                  
                              if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                                   (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
                              {
                                  // ... and the connection is on-demand (or on-traffic) if the
                                  //     calling application is using the CFSocketStream or higher APIs.
                  
                                  if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                                  {
                                      // ... and no [user] intervention is needed
                                      return YES;
                                  }
                              }
                  
                  //            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
                  //            {
                  //                // ... but WWAN connections are OK if the calling application
                  //                //     is using the CFNetwork (CFSocketStream?) APIs.
                  //                return YES;
                  //            }
                          }
                      }
                  
                          return NO;
                    //  return result;
                  }
                  
                  B Offline
                  B Offline
                  Bonnie
                  wrote on 28 Jan 2021, 07:20 last edited by
                  #8

                  @euchkatzl said in How to check whether the computer connects the internet?:

                  It is really no good idea to ping google for detecting a working internet connection.
                  Your customers will have to verify that they are not a bot on every google search afterwards.

                  Besides that, it will also not work in some countries where google is blocked.

                  1 Reply Last reply
                  1
                  • E euchkatzl
                    28 Jan 2021, 07:00

                    It is really no good idea to ping google for detecting a working internet connection.
                    Your customers will have to verify that they are not a bot on every google search afterwards.

                    I have done this depending on the platform in native code:

                    Windows:

                    bool ReachabilityCheck::internetAvailable()
                    {
                        bool result = true;
                    
                        DWORD lpresult;
                        BOOL winresult = InternetGetConnectedState(&lpresult,0);
                        result = winresult == 1 ? true : false;
                    
                        return result;
                    }
                    

                    macOS:

                    bool ReachabilityCheck::internetAvailable()
                    {
                        struct sockaddr_in zeroAddress;
                        bzero(&zeroAddress, sizeof(zeroAddress));
                        zeroAddress.sin_len = sizeof(zeroAddress);
                        zeroAddress.sin_family = AF_INET;
                    
                        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
                        if (reachability != NULL) {
                            //NetworkStatus retVal = NotReachable;
                            SCNetworkReachabilityFlags flags;
                            if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
                                if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
                                {
                                    // If target host is not reachable
                                    return NO;
                                }
                    
                                if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
                                {
                                    // If target host is reachable and no connection is required
                                    //  then we'll assume (for now) that your on Wi-Fi
                                    return YES;
                                }
                    
                    
                                if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                                     (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
                                {
                                    // ... and the connection is on-demand (or on-traffic) if the
                                    //     calling application is using the CFSocketStream or higher APIs.
                    
                                    if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                                    {
                                        // ... and no [user] intervention is needed
                                        return YES;
                                    }
                                }
                    
                    //            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
                    //            {
                    //                // ... but WWAN connections are OK if the calling application
                    //                //     is using the CFNetwork (CFSocketStream?) APIs.
                    //                return YES;
                    //            }
                            }
                        }
                    
                            return NO;
                      //  return result;
                    }
                    
                    H Offline
                    H Offline
                    hbatalha
                    wrote on 10 Feb 2021, 11:03 last edited by
                    #9
                    This post is deleted!
                    1 Reply Last reply
                    0
                    • E euchkatzl
                      28 Jan 2021, 07:00

                      It is really no good idea to ping google for detecting a working internet connection.
                      Your customers will have to verify that they are not a bot on every google search afterwards.

                      I have done this depending on the platform in native code:

                      Windows:

                      bool ReachabilityCheck::internetAvailable()
                      {
                          bool result = true;
                      
                          DWORD lpresult;
                          BOOL winresult = InternetGetConnectedState(&lpresult,0);
                          result = winresult == 1 ? true : false;
                      
                          return result;
                      }
                      

                      macOS:

                      bool ReachabilityCheck::internetAvailable()
                      {
                          struct sockaddr_in zeroAddress;
                          bzero(&zeroAddress, sizeof(zeroAddress));
                          zeroAddress.sin_len = sizeof(zeroAddress);
                          zeroAddress.sin_family = AF_INET;
                      
                          SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
                          if (reachability != NULL) {
                              //NetworkStatus retVal = NotReachable;
                              SCNetworkReachabilityFlags flags;
                              if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
                                  if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
                                  {
                                      // If target host is not reachable
                                      return NO;
                                  }
                      
                                  if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
                                  {
                                      // If target host is reachable and no connection is required
                                      //  then we'll assume (for now) that your on Wi-Fi
                                      return YES;
                                  }
                      
                      
                                  if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                                       (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
                                  {
                                      // ... and the connection is on-demand (or on-traffic) if the
                                      //     calling application is using the CFSocketStream or higher APIs.
                      
                                      if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                                      {
                                          // ... and no [user] intervention is needed
                                          return YES;
                                      }
                                  }
                      
                      //            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
                      //            {
                      //                // ... but WWAN connections are OK if the calling application
                      //                //     is using the CFNetwork (CFSocketStream?) APIs.
                      //                return YES;
                      //            }
                              }
                          }
                      
                              return NO;
                        //  return result;
                      }
                      
                      H Offline
                      H Offline
                      hbatalha
                      wrote on 10 Feb 2021, 12:05 last edited by
                      #10

                      @euchkatzl
                      Will the macOS code work on linux?? I don't have linux installed to test it yet

                      S 1 Reply Last reply 10 Feb 2021, 12:11
                      0
                      • H hbatalha
                        10 Feb 2021, 12:05

                        @euchkatzl
                        Will the macOS code work on linux?? I don't have linux installed to test it yet

                        S Offline
                        S Offline
                        sierdzio
                        Moderators
                        wrote on 10 Feb 2021, 12:11 last edited by
                        #11

                        @hbatalha said in How to check whether the computer connects the internet?:

                        @euchkatzl
                        Will the macOS code work on linux?? I don't have linux installed to test it yet

                        No, SCNetworkReachabilityRef is only available on macOS.

                        (Z(:^

                        H 1 Reply Last reply 11 Feb 2021, 19:08
                        2
                        • Q Qingshui Kong
                          18 Jan 2019, 09:16

                          Hello everybody,

                          Could somebody give me some advice?

                          I want to check whether the computer connects to the internet. And I find some answer on the internet. But they don't work well.

                          1. Use QNetworkConfigurationManager::isOnline(). It doesn't work. Sometimes it returns true even if I disconnect the internet and doesn't receive any onlineStateChanged signal(on windows system). And sometimes it returns true even though I disconnect the internet and can receive some onlineStateChanged signal, and it often receive a disconnect signal before receive an online signal(on ubuntu system). So I think it doesn't work.

                          2. Use QHostInfo::lookupHost(). It works! But if I disconnect the internet it returns online for several minutes, and if I connect the internet it returns online immediately. And if I use command (dig) on the terminal, it returns disconnect immediately after I disconnect the internet.
                            Do I make some mistake?

                          Could somebody give me some other solutions?

                          I just want to check the internet state as soon as possible.

                          Thank you in advance!

                          K Offline
                          K Offline
                          Ketan__Patel__0011
                          wrote on 10 Feb 2021, 12:31 last edited by Ketan__Patel__0011 2 Oct 2021, 12:31
                          #12

                          @Qingshui-Kong

                          if you want to check your computer is connected with the internet or not

                          Then Try this ::

                              QNetworkAccessManager nam;
                              QNetworkRequest req(QUrl("http://www.google.com"));
                              QNetworkReply* reply = nam.get(req);
                              QEventLoop loop;
                              QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
                              loop.exec();
                          
                                         if (reply->bytesAvailable())
                                         {
                                              /// You are Connected With The Internet
                                         }
                                         else
                                         {
                                              /// You Are Not Connected With The Internet
                                         }
                          
                          said_osloS 1 Reply Last reply 9 Apr 2021, 10:34
                          1
                          • S sierdzio
                            10 Feb 2021, 12:11

                            @hbatalha said in How to check whether the computer connects the internet?:

                            @euchkatzl
                            Will the macOS code work on linux?? I don't have linux installed to test it yet

                            No, SCNetworkReachabilityRef is only available on macOS.

                            H Offline
                            H Offline
                            hbatalha
                            wrote on 11 Feb 2021, 19:08 last edited by hbatalha 2 Nov 2021, 19:09
                            #13

                            @sierdzio thanks, do you know the linux version of that code?

                            @Ketan__Patel__0011 read @euchkatzl 's answer above

                            K 1 Reply Last reply 11 Feb 2021, 21:09
                            0
                            • H hbatalha
                              11 Feb 2021, 19:08

                              @sierdzio thanks, do you know the linux version of that code?

                              @Ketan__Patel__0011 read @euchkatzl 's answer above

                              K Offline
                              K Offline
                              Ketan__Patel__0011
                              wrote on 11 Feb 2021, 21:09 last edited by
                              #14

                              @hbatalha

                              Same Code Working with in All Platforms

                              1 Reply Last reply
                              0
                              • J Offline
                                J Offline
                                Jerome Godbout
                                wrote on 19 Feb 2021, 15:13 last edited by
                                #15

                                I haven't found anything reliable so far that could cover desktop and mobile device. I have a custom web server (hope for a good uptime) that I monitor, can also make a fallback and check 2 different server when both don't answer, you can suppose the internet connection is off. Better to check you own server you want to talk too. The server might be down but not the internet.

                                I wish I could avoid timeout request when no internet connection is present, the OS is aware of that, just need a way to get the information that is cross platform (that will be so useful). If anybody have an implementation that cover multiple platofrm (the Windows and Mac OS above are a good start, wonder if the Mac OS one work into iOS. WOuld still need Linux and Android to cover the most popular one at least.

                                1 Reply Last reply
                                0
                                • K Ketan__Patel__0011
                                  10 Feb 2021, 12:31

                                  @Qingshui-Kong

                                  if you want to check your computer is connected with the internet or not

                                  Then Try this ::

                                      QNetworkAccessManager nam;
                                      QNetworkRequest req(QUrl("http://www.google.com"));
                                      QNetworkReply* reply = nam.get(req);
                                      QEventLoop loop;
                                      QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
                                      loop.exec();
                                  
                                                 if (reply->bytesAvailable())
                                                 {
                                                      /// You are Connected With The Internet
                                                 }
                                                 else
                                                 {
                                                      /// You Are Not Connected With The Internet
                                                 }
                                  
                                  said_osloS Offline
                                  said_osloS Offline
                                  said_oslo
                                  wrote on 9 Apr 2021, 10:34 last edited by said_oslo 4 Dec 2021, 12:53
                                  #16

                                  @Ketan__Patel__0011 said in How to check whether the computer connects the internet?:

                                  @Qingshui-Kong
                                  if you want to check your computer is connected with the internet or not
                                  Then Try this ::
                                  QNetworkAccessManager nam;
                                  QNetworkRequest req(QUrl("http://www.google.com"));
                                  QNetworkReply* reply = nam.get(req);
                                  QEventLoop loop;
                                  QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
                                  loop.exec();

                                             if (reply->bytesAvailable())
                                             {
                                                  /// You are Connected With The Internet
                                             }
                                             else
                                             {
                                                  /// You Are Not Connected With The Internet
                                             }
                                  

                                  Hi.
                                  It's not good idea to ping google.com for detecting the internet connection status.

                                  Because i have tested (I use qt_app inside Debian 9) and measured a bandwidth used by google.com and telenor.no then as conclusions:

                                  They consume a lot bandwidth in idle mode (google.com bandwidth = 3 * telenor.no).

                                  I'm looking for a method for detecting internet connection status without be dependent to any server.

                                  Please share if there are other idea without using QNetworkAccessManager

                                  K H 2 Replies Last reply 9 Apr 2021, 17:25
                                  0
                                  • said_osloS said_oslo
                                    9 Apr 2021, 10:34

                                    @Ketan__Patel__0011 said in How to check whether the computer connects the internet?:

                                    @Qingshui-Kong
                                    if you want to check your computer is connected with the internet or not
                                    Then Try this ::
                                    QNetworkAccessManager nam;
                                    QNetworkRequest req(QUrl("http://www.google.com"));
                                    QNetworkReply* reply = nam.get(req);
                                    QEventLoop loop;
                                    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
                                    loop.exec();

                                               if (reply->bytesAvailable())
                                               {
                                                    /// You are Connected With The Internet
                                               }
                                               else
                                               {
                                                    /// You Are Not Connected With The Internet
                                               }
                                    

                                    Hi.
                                    It's not good idea to ping google.com for detecting the internet connection status.

                                    Because i have tested (I use qt_app inside Debian 9) and measured a bandwidth used by google.com and telenor.no then as conclusions:

                                    They consume a lot bandwidth in idle mode (google.com bandwidth = 3 * telenor.no).

                                    I'm looking for a method for detecting internet connection status without be dependent to any server.

                                    Please share if there are other idea without using QNetworkAccessManager

                                    K Offline
                                    K Offline
                                    Ketan__Patel__0011
                                    wrote on 9 Apr 2021, 17:25 last edited by
                                    #17

                                    @said_oslo

                                    Yes You Can also use Ping

                                    Like this

                                    if(QProcess::execute("ping -n 1 www.google.com") == 0)
                                    {
                                           // You Are Connected With The Internet.
                                    }
                                    else
                                    {
                                           // You Are Not Connected With The Internet.
                                    }
                                    
                                    said_osloS 1 Reply Last reply 30 Apr 2021, 07:07
                                    0
                                    • E euchkatzl
                                      28 Jan 2021, 07:00

                                      It is really no good idea to ping google for detecting a working internet connection.
                                      Your customers will have to verify that they are not a bot on every google search afterwards.

                                      I have done this depending on the platform in native code:

                                      Windows:

                                      bool ReachabilityCheck::internetAvailable()
                                      {
                                          bool result = true;
                                      
                                          DWORD lpresult;
                                          BOOL winresult = InternetGetConnectedState(&lpresult,0);
                                          result = winresult == 1 ? true : false;
                                      
                                          return result;
                                      }
                                      

                                      macOS:

                                      bool ReachabilityCheck::internetAvailable()
                                      {
                                          struct sockaddr_in zeroAddress;
                                          bzero(&zeroAddress, sizeof(zeroAddress));
                                          zeroAddress.sin_len = sizeof(zeroAddress);
                                          zeroAddress.sin_family = AF_INET;
                                      
                                          SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
                                          if (reachability != NULL) {
                                              //NetworkStatus retVal = NotReachable;
                                              SCNetworkReachabilityFlags flags;
                                              if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
                                                  if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
                                                  {
                                                      // If target host is not reachable
                                                      return NO;
                                                  }
                                      
                                                  if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
                                                  {
                                                      // If target host is reachable and no connection is required
                                                      //  then we'll assume (for now) that your on Wi-Fi
                                                      return YES;
                                                  }
                                      
                                      
                                                  if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                                                       (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
                                                  {
                                                      // ... and the connection is on-demand (or on-traffic) if the
                                                      //     calling application is using the CFSocketStream or higher APIs.
                                      
                                                      if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                                                      {
                                                          // ... and no [user] intervention is needed
                                                          return YES;
                                                      }
                                                  }
                                      
                                      //            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
                                      //            {
                                      //                // ... but WWAN connections are OK if the calling application
                                      //                //     is using the CFNetwork (CFSocketStream?) APIs.
                                      //                return YES;
                                      //            }
                                              }
                                          }
                                      
                                              return NO;
                                        //  return result;
                                      }
                                      
                                      H Offline
                                      H Offline
                                      hbatalha
                                      wrote on 15 Apr 2021, 20:35 last edited by
                                      #18

                                      @euchkatzl InternetGetConnectedState is not recommended by Microsoft, it is recommended to use INetworkListManager::GetConnectivity instead.

                                      Here is an example I found.

                                      1 Reply Last reply
                                      1
                                      • said_osloS said_oslo
                                        9 Apr 2021, 10:34

                                        @Ketan__Patel__0011 said in How to check whether the computer connects the internet?:

                                        @Qingshui-Kong
                                        if you want to check your computer is connected with the internet or not
                                        Then Try this ::
                                        QNetworkAccessManager nam;
                                        QNetworkRequest req(QUrl("http://www.google.com"));
                                        QNetworkReply* reply = nam.get(req);
                                        QEventLoop loop;
                                        QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
                                        loop.exec();

                                                   if (reply->bytesAvailable())
                                                   {
                                                        /// You are Connected With The Internet
                                                   }
                                                   else
                                                   {
                                                        /// You Are Not Connected With The Internet
                                                   }
                                        

                                        Hi.
                                        It's not good idea to ping google.com for detecting the internet connection status.

                                        Because i have tested (I use qt_app inside Debian 9) and measured a bandwidth used by google.com and telenor.no then as conclusions:

                                        They consume a lot bandwidth in idle mode (google.com bandwidth = 3 * telenor.no).

                                        I'm looking for a method for detecting internet connection status without be dependent to any server.

                                        Please share if there are other idea without using QNetworkAccessManager

                                        H Offline
                                        H Offline
                                        hbatalha
                                        wrote on 16 Apr 2021, 05:07 last edited by hbatalha
                                        #19

                                        @said_oslo This is what I am using:

                                        bool nternetAvailable()
                                        {
                                        #ifdef Q_OS_WIN
                                        
                                            INetworkListManager* inlm;
                                        
                                            HRESULT hr = CoCreateInstance(CLSID_NetworkListManager, NULL,
                                                                          CLSCTX_ALL, IID_INetworkListManager,
                                                                          (LPVOID *)&inlm);
                                            if (SUCCEEDED(hr))
                                            {
                                                NLM_CONNECTIVITY con;
                                        
                                                hr = inlm->GetConnectivity(&con);
                                        
                                                if(hr == S_OK)
                                                {
                                                    if (con & NLM_CONNECTIVITY_IPV4_INTERNET || con & NLM_CONNECTIVITY_IPV6_INTERNET)
                                                        return true;
                                                    else
                                                        return false;
                                                }
                                            }
                                            
                                            // default
                                            return true;
                                        
                                        #elif defined Q_OS_LINUX
                                        
                                            FILE *output;
                                        
                                            if(!(output = popen("/sbin/route -n | grep -c '^0\\.0\\.0\\.0'","r")))
                                            {
                                                return 1;
                                            }
                                            unsigned int i;
                                            fscanf(output,"%u",&i);
                                        
                                            pclose(output);
                                        
                                            if(i==0)
                                                return false;
                                            else if(i==1)
                                                return true;
                                        
                                        #endif
                                        }
                                        

                                        Use these headers(must be in this order)

                                        #ifdef Q_OS_WIN
                                        #include <initguid.h>
                                        #include <netlistmgr.h>
                                        #endif
                                        
                                        1 Reply Last reply
                                        0
                                        • Qterry.wangQ Offline
                                          Qterry.wangQ Offline
                                          Qterry.wang
                                          wrote on 16 Apr 2021, 11:00 last edited by
                                          #20

                                          hi Brother,look this:

                                          void ThreadObject::pingNetwork(QString remotIP)
                                          {
                                          QProcess cmd; //类似于window里面的cmd命令
                                          QTextCodec *codec = QTextCodec::codecForName("GBK");
                                          QString outstr;

                                          QString pingString="ping "+ remotIP + " -n 1";
                                          cmd.start(pingString);	//ping ip地址 -n 1表示只ping一次就结束
                                          cmd.waitForFinished(-1);			//等待ping完成
                                          outstr = codec->toUnicode(cmd.readAll());	//将ping之后的结果全部读到outstr中
                                          if(-1!=outstr.indexOf("往返行程的估计时间"))	//通过判断有无“往返行程的估计时间”这几个字来检测网路是否通
                                          {
                                              qDebug() << "connect success!";
                                              emit signal_networkstate(true);	//发送网络连接的信号
                                          }
                                          else
                                          {
                                              qDebug() << "connect failed!";
                                              emit signal_networkstate(false);	//发送网络断开的信号
                                          }
                                          

                                          }

                                          just change the URL to any one you like. thank you

                                          Have a good day !

                                          H 1 Reply Last reply 16 Apr 2021, 13:52
                                          0

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved