本文介绍了使用Qt 4.4验证网络连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个应用程序,该应用程序运行需要网络连接的工具.现在,我的目的是检查用户是否具有网络连接,如果他没有网络连接,我可以立即显示错误,而无需进一步进行操作.如果有,他可以继续使用我的应用程序.因此,我的基本需求是检查用户是否具有网络连接.如何通过Qt 4.4实现?我正在使用Windows XP.
I have an application which runs a tool that requires network connection. Now my aim is to check whether the user has a network connection, if he don't have one, i can straight away display an error without proceeding further. If he has, he can continue working with my application. So my basic need is to check whether the user has a network connection or not. How i can achieve through Qt 4.4? I am using Windows XP.
推荐答案
此代码将为您提供帮助.
this code will help you.
#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 4.4验证网络连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!