Live2D

C++代码读取ping的网络延时

利用C++代码实现读取ping工具的网络延时数据

 

直接上代码

#include <QCoreApplication>
#include <QTextCodec>
#include <QProcess>
#include <iostream>
#include <Windows.h>


void checkOnline( QString ip )
{
  QProcess exc;
  QTextCodec* codec = QTextCodec::codecForName( "GBK" );
  QString cmdstr = "ping " + ip; //ping 192.168.15.90  -n 2 -w 4000
  while ( true )
  {
    exc.start( cmdstr ); //执行ping
    exc.waitForFinished( -1 ); //等待ping完成
    QString  outstr = codec->toUnicode( exc.readAll() ); //获取ping结果
    //返回不等于-1,说明ping结果包含"往返行程的估计时间"字段,则说明ping成功,网络可达;等于-1,表示没有此字段,说明ping不通
    QString test = "ms";
    int flag = outstr.indexOf( test );
    if ( ( -1 != flag ) )
    {
      int start_num = flag - 1;
      while ( true )
      {
        if ( outstr.mid( start_num - 1, 1 ) == "<" || outstr.mid( start_num - 1, 1 ) == "=" )
        {
          break;
        }
        start_num --;
      }
      QString time = outstr.mid( start_num, flag - start_num );
      std::cout << time.toStdString() << std::endl;
      qDebug( "Online\n" );
    }
    else
    {
      qDebug( "Offline\n" );
    }
  }
}
int main( int argc, char* argv[] )
{
  QCoreApplication a( argc, argv );
  checkOnline( "192.168.15.90" );

  return a.exec();
}

代码运行结果如下

 

posted @ 2020-04-30 16:36  檀木  阅读(1675)  评论(0编辑  收藏  举报
//一下两个链接最好自己保存下来,再上传到自己的博客园的“文件”选项中