Qt 判断网络连接

来源:互联网 发布:java计算a阶乘之和 编辑:程序博客网 时间:2024/06/01 19:36

前言

在Qt中判断网络是否连接有两种方式,其中一种是网络连接但是不一定能上网,可能只是连接了网线或者Wi-Fi,但不一定能够上互联网。另一种判断该网络是否可以连接互联网,两种情况的判别方式有所区别。

正文

第一种:只需要判断网络是否有连接,不一定能上网

这个很简单,直接通过Qt的类QNetworkConfigurationManager自带的函数就可以判断(该方法也适用于Android平台):

bool CommonParameter::isNetWorkOnline(){    QNetworkConfigurationManager mgr;    return mgr.isOnline();}

第二种:判断是否能上网

这种方式是检查是否连接互联网,原理:通过访问指定的网站,如果能访问成功表示已正常连接。

void CommonParameter::checkNetWorkOnline(){    QHostInfo::lookupHost("www.baidu.com",this,SLOT(onLookupHost(QHostInfo)));}void CommonParameter::onLookupHost(QHostInfo host){    if (host.error() != QHostInfo::NoError) {        qDebug() << "Lookup failed:" << host.errorString();        //网络未连接,发送信号通知        emit sigLookUpHostResult(false);    }    else{        emit sigLookUpHostResult(true);    }}

通过静态函数QHostInfo::lookupHost访问指定网络后会将结果返回到槽里面,然后再将结果发送信号出去。

监测网络变化

第一种方法可以获取到当前网络状态,但是如果要实时监测到网络变化,可以通过QNetworkConfigurationManager中的信号来获取,如下

void onlineStateChanged(bool isOnline)

官方说明:This signal is emitted when the device changes from online to offline mode or vice versa. isOnline represents the new state of the device.
The state is considered to be online for as long as allConfigurations(QNetworkConfiguration::Active) returns a list with at least one entry.
所以,可以通过连接这个信号来实现网络监测,亲测可用。

0 0
原创粉丝点击