代码之家  ›  专栏  ›  技术社区  ›  liaK

使用qt4.4验证网络连接

  •  6
  • liaK  · 技术社区  · 16 年前

    3 回复  |  直到 16 年前
        1
  •  10
  •   Muhammad Anjum Kaiser    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();
    }
    
        2
  •  1
  •   chalup    16 年前

    我假设“网络连接”的意思是“互联网连接”,也就是说,你不关心你的桌面和移动设备之间的局域网或一些特殊网络。

    最简单的方法就是连接到应用程序所需的internet服务,并让操作系统处理网络请求。如果你得到回复,有一个连接,如果请求超时,没有连接。

    您可以通过QNetworkInterface::flags()检查网络接口的状态,但这并不能提供有关接口连接到的网络的信息:接口可能已启动,但仅连接到LAN而没有internet访问。

        3
  •  1
  •   CHW mmoment    10 年前