我有一个运行需要网络连接的工具的应用程序。现在,我的目标是检查用户是否具有网络连接,如果他没有网络连接,我可以立即显示错误,而无需进一步进行操作。如果有,他可以继续使用我的应用程序。因此,我的基本需求是检查用户是否具有网络连接。如何通过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();
}

08-07 20:02