利用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(); }
代碼運行結果如下