我有一个运行需要网络连接的工具的应用程序。现在我的目标是检查用户是否有网络连接,如果他没有网络连接,我可以立即显示一个错误,而不会继续。如果他有,他可以继续使用我的应用程序。所以我的基本需求是检查用户是否有网络连接。如何通过Qt 4.4实现?我使用的是Windows XP。
发布于 2010-03-19 16:35:16
此代码将对您有所帮助。
#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();
}发布于 2010-03-19 15:32:04
我假设你所说的“网络连接”指的是“互联网连接”,也就是说,你并不关心你的桌面和移动设备之间的局域网或一些临时网络。
最简单的方法是连接到您的应用程序所需的internet服务,并让操作系统处理网络请求。如果您得到回复,则有一个连接,如果请求超时,则没有连接。
您可以通过QNetworkInterface::flag()检查网络接口的状态,但这不会给您提供有关接口所连接到的网络的信息:接口可能处于打开状态,但仅连接到LAN,而不能访问internet。
发布于 2010-09-09 16:15:08
在Qt4.7中,你可以使用QNetworkConfiguration来检查连接,甚至在Symbian上启动它们。
https://stackoverflow.com/questions/2475266
复制相似问题