我有一个运行需要网络连接的工具的应用程序。现在我的目标是检查用户是否有网络连接,如果没有网络连接,我可以立即显示错误而无需进一步操作。如果他有,他可以继续处理我的申请。所以我的基本需求是检查用户是否有网络连接。我如何通过Qt 4.4实现?我使用的是 Windows XP。
最佳答案
此代码将为您提供帮助。
#include <QtCore/QCoreApplication>
#include <QtNetwork/QNetworkInterface>
bool isConnectedToNetwork()
{
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
bool result = false;
for (int i = 0; i < ifaces.count(); i++)
{
QNetworkInterface iface = ifaces.at(i);
if ( iface.flags().testFlag(QNetworkInterface::IsUp)
&& !iface.flags().testFlag(QNetworkInterface::IsLoopBack) )
{
#ifdef DEBUG
// details of connection
qDebug() << "name:" << iface.name() << endl
<< "ip addresses:" << endl
<< "mac:" << iface.hardwareAddress() << endl;
#endif
// this loop is important
for (int j=0; j<iface.addressEntries().count(); j++)
{
#ifdef DEBUG
qDebug() << iface.addressEntries().at(j).ip().toString()
<< " / " << iface.addressEntries().at(j).netmask().toString() << endl;
#endif
// we have an interface that is up, and has an ip address
// therefore the link is present
// we will only enable this check on first positive,
// all later results are incorrect
if (result == false)
result = true;
}
}
}
return result;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextStream output(stdout);
output << endl << "Connection Status: " << ((isConnectedToNetwork())?"Connected":"Disconnected") << endl;
return a.exec();
}
关于qt - 使用 Qt 4.4 验证网络连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2475266/