qt - 使用 Qt 4.4 验证网络连接

标签 qt networking

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

相关文章:

c++ - QReadWriteLock递归

c++ - 使用Qt打印功能

c++ - QTreeView:多级列的层次上下文

c++ - Qt项目中如何使用预编译头文件

ios - UIView 子类(自定义进度 View )不会显示,直到为时已晚

Linux:桥上的端口隔离以正确使用 OLSR

networking - 是否可以重复或重新分配蓝牙信号?

c++ - 如何在 C++ 和 QML 应用程序中使用 qrc?

Docker:如何使用 docker-compose 而不使用 iptables 来防止来自 docker 网络的传出流量?

delphi - 检测到机器是否已连接/可用?