Get the ping from a remote target with Qt (Windows/Linux)

前端 未结 4 2717
不知归路
不知归路 2021-02-20 17:19

Currently I use this code for retrieving the ping of a target system. However it works so far only under linux and it is likely dependent on the locale settings. To add suppor

4条回答
  •  不思量自难忘°
    2021-02-20 17:47

    The ping method return a 0 exit code event if the target is unreachable in Windows. You have to parse the command output. The following example is working on Windows and linux :

    class MyClass {
      private slots:
       void OnPing();
       void OnPingEnded();
      private:
       Process mPingProcess;
    };
    
    void MyClass::OnPing()
    {
       connect(&mPingProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(OnPingEnded()));
    #ifdef __linux__
       mPingProcess.start("ping", QStringList() << "-c" << "1" << ui->ip->text());
    #else
       mPingProcess.start("ping", QStringList() << "-n" << "1" << ui->ip->text());
    #endif
    }
    
    void MyClass::OnPingEnded()
    {
        QByteArray output = mPingProcess.readAllStandardOutput();
        if (!output.isEmpty())
        {
            qDebug() << output;
            if (-1 != QString(output).indexOf("ttl", 0, Qt::CaseInsensitive))
            {
               qDebug() << "PING OK";
            }
            else
            {
               qDebug() << "PING KO";
            }
        }
    }
    

提交回复
热议问题