windos平台Qt实现ping检测网络连通性
#include <QApplication>
#include <Windows.h>
#include <Sensapi.h>
#include <Wininet.h>
#include<qDebug>
#include <QTextCodec>
#include<QProcess>
#pragma comment(lib,"Sensapi.lib")
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QProcess exc;
QTextCodec *codec = QTextCodec::codecForName("GBK");
QString cmdstr="ping 192.168.110.179";//ping 192.168.110.179 -n 2 -w 4000
exc.start(cmdstr);//执行ping
exc.waitForFinished(-1);//等待ping完成
QString outstr=codec->toUnicode(exc.readAll());//获取ping结果
//返回不等于-1,说明ping结果包含"往返行程的估计时间"字段,则说明ping成功,网络可达;等于-1,表示没有此字段,说明ping不通
if((-1 !=outstr.indexOf("往返行程的估计时间")))
{
qDebug("在线\n");
}else
{
qDebug("离线\n");
}
return a.exec();
}
linux平台c++实现ping检测网络连通性
#include<stdio.h>#include<iostream>
#include <stdlib.h>
using namespace std;
int main() {
//-c 指定ping次数; -i指定ping的时间间隔
string strping = "ping -c 3 -i 0.5 ";
string strip[3] = { "192.168.110.179", "192.168.0.1", "192.168.122.1"};
for (int i = 0; i < 3; i++) {
string tmp = strping + strip[i];
if (!system(tmp.c_str())) {
cout << "ping " << strip[i] << ",success!\n";
} else {
cout << "ping " << strip[i] << ",failed!\n";
}
}
return 0;
}