1. 判断网络连接,但不一定能上网
QNetworkConfigurationManager
bool NetCheck::checkNetworkConnect()
{
QNetworkConfigurationManager netMgr;
if (netMgr.isOnline())
{
qDebug() << "Connected!" << endl;
return true;
}
else
{
qDebug() << "Not Connected!" << endl;
return false;
}
}
2. 判断能否上网
QHostInfo
void NetCheck::checkNetworkOnline()
{
QHostInfo::lookupHost("www.baidu.com", this, SLOT(lookupHostSlot(QHostInfo)));
}
void NetCheck::lookupHostSlot(QHostInfo host)
{
if (host.error() != QHostInfo::NoError)
{
qDebug() << "Not Online! " + host.errorString() << endl;
}
else
{
qDebug() << "Online!" << endl;
}
}
有网络连接但不能上网时,会等待几秒出结果
3. 网络状态变化
QNetworkConfigurationManager
QNetworkConfigurationManager mgr;
connect(&mgr, SIGNAL(onlineStateChanged(bool)), this, SLOT(onlineStateChangedSlot(bool)));
void NetCheck::onlineStateChangedSlot(bool state)
{
if (state)
qDebug() << "Changed to Online!" << endl;
else
qDebug() << "Changed to Offline!" << endl;
}
评论区