如何在Qt中监控互联网连接状态?我的意思是,我想能够根据互联网连接的存在与否来更改图标为活动/非活动状态。
我在使用类似 Winston Rodrigues 和Flatpak 的解决方案时遇到了问题。这个解决方案在我测试的几乎所有电脑上都可以运行,但有一个电脑无法检测到网络连接,而且没有任何错误提示。因此,这是目前在所有情况下都适用于我的解决方案:
bool InternetIsOn()
{
QUrl host("1.1.1.1"); // put here URL (or IP) of your own website if you have one
qDebug() << tr("Checking internet connection: connecting to %1 ...").arg(host.toString());
QTcpSocket* sock = new QTcpSocket(this);
connect(sock, &QTcpSocket::errorOccurred, this, [](QAbstractSocket::SocketError error) {
qDebug() << "This error occured during Internet checking:" << error;
});
sock->connectToHost(host.toString(), 80);
bool connected = sock->waitForConnected(3'000);//ms
if (!connected)
{
sock->abort();
qDebug() << tr("%1 is not reachable. Not connected to the Internet").arg(host.toString());
return false;
}
sock->close();
qDebug() << tr("Connected to the Internet");
return true;
}
bool ConnectivityManager::isOnline()
{
bool retVal = false;
QNetworkAccessManager nam;
QNetworkRequest req(QUrl("http://www.google.com"));
QNetworkReply* reply = nam.get(req);
QEventLoop loop;
QTimer timeoutTimer;
connect(&timeoutTimer, SIGNAL(timeout()), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
timeoutTimer.setSingleShot(true);
timeoutTimer.start(3000);
loop.exec();
if (reply->bytesAvailable())
{
retVal = true;
}
return retVal;
}