QNetworkInformation 類

QNetworkInformation 透過本機後端暴露各種網絡信息。 更多...

頭: #include <QNetworkInformation>
CMake: find_package(Qt6 REQUIRED COMPONENTS Network)
target_link_libraries(mytarget PRIVATE Qt6::Network)
qmake: QT += network
Since: Qt 6.1
繼承: QObject

公共類型

枚舉類 Feature { Reachability, CaptivePortal, TransportMedium, Metered }
flags Features
枚舉類 Reachability { Unknown, Disconnected, Local, Site, Online }
(從 6.3 起) 枚舉類 TransportMedium { Unknown, Ethernet, Cellular, WiFi, Bluetooth }

特性

公共函數

QString backendName () const
bool isBehindCaptivePortal () const
bool isMetered () const
QNetworkInformation::Reachability reachability () const
(從 6.3 起) QNetworkInformation::Features supportedFeatures () const
bool supports (QNetworkInformation::Features features ) const
QNetworkInformation::TransportMedium transportMedium () const

信號

void isBehindCaptivePortalChanged (bool state )
void isMeteredChanged (bool isMetered )
void reachabilityChanged (QNetworkInformation::Reachability newReachability )
void transportMediumChanged (QNetworkInformation::TransportMedium current )

靜態公共成員

QStringList availableBackends ()
QNetworkInformation * instance ()
(從 6.4 起) bool loadBackendByFeatures (QNetworkInformation::Features features )
(從 6.4 起) bool loadBackendByName (QStringView backend )
(從 6.3 起) bool loadDefaultBackend ()

詳細描述

QNetworkInformation provides a cross-platform interface to network-related information through plugins.

Various plugins can have various functionality supported, and so you can load plugins based on which features are needed.

In most cases, the recommended approach is to load the platform-specific backend by calling loadDefaultBackend (). This will automatically select the most appropriate backend available on the current platform and is suitable for the majority of applications.

#include <QCoreApplication>
#include <QNetworkInformation>
#include <QDebug>
void onReachabilityChanged(QNetworkInformation::Reachability reachability) {
    switch (reachability) {
    case QNetworkInformation::Reachability::Unknown:
        qDebug() << "Network reachability is unknown.";
        break;
    case QNetworkInformation::Reachability::Disconnected:
        qDebug() << "Network is disconnected.";
        break;
    case QNetworkInformation::Reachability::Local:
        qDebug() << "Network is locally reachable.";
        break;
    case QNetworkInformation::Reachability::Site:
        qDebug() << "Network can reach the site.";
        break;
    case QNetworkInformation::Reachability::Online:
        qDebug() << "Network is online.";
        break;
    }
}
int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);
    // Check if QNetworkInformation is supported
    if (!QNetworkInformation::loadDefaultBackend()) {
        qWarning() << "QNetworkInformation is not supported on this platform or backend.";
        return 1;
    }
    QNetworkInformation* netInfo = QNetworkInformation::instance();
    // Connect to the reachabilityChanged signal
    QObject::connect(netInfo, &QNetworkInformation::reachabilityChanged,
                     &onReachabilityChanged);
    // Print initial status
    onReachabilityChanged(netInfo->reachability());
    return a.exec();
}
					

For more advanced uses cases, developers may prefer to load a backend based on specific capabilities or preferences. loadBackendByFeatures () allows selecting a backend that supports a specific set of features, such as reporting the transport mediom or signal strength. Alternatively, loadBackendByName () allows loading a plugin by its name, which can include platform-specific or custom backend implementations.

QNetworkInformation is a singleton and stays alive from the first successful load until destruction of the QCoreApplication object. If you destroy and re-create the QCoreApplication object you must load it again to reinitialize the plugin.

注意: Because the class is a singleton while also relying on QCoreApplication , QNetworkInformation should always first be loaded in the same thread as the QCoreApplication object. This is because the object will also be destroyed in this thread, and various backend-specific components may rely on being destroyed in the same thread as it is created.

One possible use case for QNetworkInformation is to monitor network connectivity status. reachability () provides an indication of whether the system is considered online, based on information reported by the underlying operating system or plugin. However, this information may not always be accurate. For example, on Windows, the online check may rely on connectivity to a Microsoft-owned server; if that server is unreachable (e.g., due to firewall rules), the system may incorrectly report that it is offline. As such, reachability () should not be used as a definitive pre-check before attempting a network connection, but rather as a general signal of connectivity state.

要使用 reachability () effectively, the application must also understand what kind of destination it is trying to reach. For example, if the target is a local IP address, then Reachability::Local or Reachability::Site may be sufficient. If the destination is on the public internet, then Reachability::Online is required. Without this context, interpretring the reported reachability may lead to incorrect assumptions about actual network access.

警告: Only Linux and Windows provide support for the finer-grained Reachability::Site and Reachability::Local options. On Android and Apple platforms reachability () is limited to reporting only Online, Offline or Unknown. Therefore, any logic that relies on detecting Local or Site level connectivity must include appropriate platform checks or fallbacks.

// Simple helper to decide whether an IP address is "local"
bool isLocalAddress(const QHostAddress &address)
{
    return address.isInSubnet(QHostAddress("192.168.0.0"), 16) ||
           address.isInSubnet(QHostAddress("10.0.0.0"), 8)     ||
           address.isInSubnet(QHostAddress("172.16.0.0"), 12)  ||
           address.isLoopback();
}
int main(int argc, char *argv[])
{
    ...
    // Target IP address (default: Google DNS)
    QString targetIpStr = argc > 1 ? argv[1] : "8.8.8.8";
    QHostAddress targetIp(targetIpStr);
    if (targetIp.isNull()) {
        qWarning() << "Invalid IP address:" << targetIpStr;
        return 1;
    }
    // Decide what level of reachability is needed for the target
    QNetworkInformation::Reachability requiredReachability =
        isLocalAddress(targetIp)
            ? QNetworkInformation::Reachability::Local
            : QNetworkInformation::Reachability::Online;
    // Fetch the current system-reported reachability
    QNetworkInformation::Reachability currentReachability = networkInfo->reachability();
    qDebug() << "Target IP:" << targetIp.toString();
    qDebug() << "Target is considered"
             << (isLocalAddress(targetIp) ? "local/site." : "external/online.");
    qDebug() << "Required reachability level:" << requiredReachability;
    qDebug() << "Current reachability:" << currentReachability;
    if (currentReachability < requiredReachability) {
        qWarning() << "Current network state may not allow reaching the target address.";
    } else {
        qDebug() << "Target may be reachable based on current network state.";
    }
    ...
					

另請參閱 QNetworkInformation::Feature .

成員類型文檔編製

enum class QNetworkInformation:: Feature
flags QNetworkInformation:: Features

Lists all of the features that a plugin may currently support. This can be used in QNetworkInformation::loadBackendByFeatures ().

常量 描述
QNetworkInformation::Feature::Reachability 0x1 若插件支持此特徵,那麼 reachability property will provide useful results. Otherwise it will always return Reachability::Unknown 。另請參閱 QNetworkInformation::Reachability .
QNetworkInformation::Feature::CaptivePortal 0x2 若插件支持此特徵,那麼 isBehindCaptivePortal property will provide useful results. Otherwise it will always return false .
QNetworkInformation::Feature::TransportMedium 0x4 若插件支持此特徵,那麼 transportMedium property will provide useful results. Otherwise it will always return TransportMedium::Unknown 。另請參閱 QNetworkInformation::TransportMedium .
QNetworkInformation::Feature::Metered 0x8 若插件支持此特徵,那麼 isMetered property will provide useful results. Otherwise it will always return false .

Features 類型是 typedef 對於 QFlags <Feature>. It stores an OR combination of Feature values.

enum class QNetworkInformation:: Reachability

常量 描述
QNetworkInformation::Reachability::Unknown 0 If this value is returned then we may be connected but the OS has still not confirmed full connectivity, or this feature is not supported.
QNetworkInformation::Reachability::Disconnected 1 Indicates that the system may have no connectivity at all.
QNetworkInformation::Reachability::Local 2 Indicates that the system is connected to a network, but it might only be able to access devices on the local network.
QNetworkInformation::Reachability::Site 3 Indicates that the system is connected to a network, but it might only be able to access devices on the local subnet or an intranet.
QNetworkInformation::Reachability::Online 4 Indicates that the system is connected to a network and able to access the Internet.

另請參閱 QNetworkInformation::reachability .

[since 6.3] enum class QNetworkInformation:: TransportMedium

Lists the currently recognized media with which one can connect to the internet.

常量 描述
QNetworkInformation::TransportMedium::Unknown 0 Returned if either the OS reports no active medium, the active medium is not recognized by Qt, or the TransportMedium feature is not supported.
QNetworkInformation::TransportMedium::Ethernet 1 Indicates that the currently active connection is using ethernet. Note: This value may also be returned when Windows is connected to a Bluetooth personal area network.
QNetworkInformation::TransportMedium::Cellular 2 Indicates that the currently active connection is using a cellular network.
QNetworkInformation::TransportMedium::WiFi 3 Indicates that the currently active connection is using Wi-Fi.
QNetworkInformation::TransportMedium::Bluetooth 4 Indicates that the currently active connection is connected using Bluetooth.

該枚舉在 Qt 6.3 引入。

另請參閱 QNetworkInformation::transportMedium .

特性文檔編製

[read-only, since 6.2] isBehindCaptivePortal : const bool

Lets you know if the user's device is behind a captive portal.

This property indicates if the user's device is currently known to be behind a captive portal. This functionality relies on the operating system's detection of captive portals and is not supported on systems that don't report this. On systems where this is not supported this will always return false .

該特性在 Qt 6.2 引入。

訪問函數:

bool isBehindCaptivePortal () const

通知程序信號:

void isBehindCaptivePortalChanged (bool state )

[read-only, since 6.3] isMetered : const bool

校驗當前連接是否有計量

This property returns whether the current connection is (known to be) metered or not. You can use this as a guiding factor to decide whether your application should perform certain network requests or uploads. For instance, you may not want to upload logs or diagnostics while this property is true .

void uploadLogFile()
{
    ...
}
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    ...
        if (netInfo->isMetered()) {
            qWarning() << "Log upload skipped: Current network is metered.";
            app.quit();
        } else {
            uploadLogFile();
        }
    ...
}
					

該特性在 Qt 6.3 引入。

訪問函數:

bool isMetered () const

通知程序信號:

void isMeteredChanged (bool isMetered )

[read-only] reachability : const Reachability

This property holds the current state of the system's network connectivity.

Indicates the level of connectivity that can be expected. Do note that this is only based on what the plugin/operating system reports. In certain scenarios this is known to be wrong. For example, on Windows the 'Online' check, by default, is performed by Windows connecting to a Microsoft-owned server. If this server is for any reason blocked then it will assume it does not have Online reachability. Because of this you should not use this as a pre-check before attempting to make a connection.

訪問函數:

QNetworkInformation::Reachability reachability () const

通知程序信號:

void reachabilityChanged (QNetworkInformation::Reachability newReachability )

[read-only, since 6.3] transportMedium : const TransportMedium

This property holds the currently active transport medium for the application

This property returns the currently active transport medium for the application, on operating systems where such information is available.

When the current transport medium changes a signal is emitted, this can, for instance, occur when a user leaves the range of a WiFi network, unplugs their ethernet cable or enables Airplane mode.

該特性在 Qt 6.3 引入。

訪問函數:

QNetworkInformation::TransportMedium transportMedium () const

通知程序信號:

void transportMediumChanged (QNetworkInformation::TransportMedium current )

成員函數文檔編製

[static] QStringList QNetworkInformation:: availableBackends ()

Returns a list of the names of all currently available backends.

QString QNetworkInformation:: backendName () const

返迴當前加載的後端名稱。

[static] QNetworkInformation *QNetworkInformation:: instance ()

Returns a pointer to the instance of the QNetworkInformation , if any. If this method is called before a backend is loaded, it returns a null pointer.

另請參閱 loadBackendByName (), loadDefaultBackend (),和 loadBackendByFeatures ().

[static, since 6.4] bool QNetworkInformation:: loadBackendByFeatures ( QNetworkInformation::Features features )

Load a backend which supports features .

返迴 true if it managed to load the requested backend or if it was already loaded. Returns false 否則。

該函數在 Qt 6.4 引入。

另請參閱 instance .

[static, since 6.4] bool QNetworkInformation:: loadBackendByName ( QStringView backend )

Attempts to load a backend whose name matches backend (case insensitively).

返迴 true if it managed to load the requested backend or if it was already loaded. Returns false 否則。

該函數在 Qt 6.4 引入。

另請參閱 instance .

[static, since 6.3] bool QNetworkInformation:: loadDefaultBackend ()

試圖加載平颱默認後端。

注意: Starting with 6.7 this tries to load any backend that supports Reachability if the platform-default backend is not available or fails to load. If this also fails it will fall back to a backend that only returns the default values for all properties.

This platform-to-plugin mapping is as follows:

平颱 插件名
Windows networklistmanager
Apple (macOS/iOS) applenetworkinformation
Android android
Linux networkmanager

This function is provided for convenience where the logic earlier is good enough. If you require a specific plugin then you should call loadBackendByName () 或 loadBackendByFeatures () directly instead.

Determines a suitable backend to load and returns true if this backend is already loaded or on successful loading of it. Returns false if any other backend has already been loaded, or if loading of the selected backend fails.

該函數在 Qt 6.3 引入。

另請參閱 instance (), loadBackendByName (),和 loadBackendByFeatures ().

[since 6.3] QNetworkInformation::Features QNetworkInformation:: supportedFeatures () const

返迴當前後端支持的所有特徵。

該函數在 Qt 6.3 引入。

bool QNetworkInformation:: supports ( QNetworkInformation::Features features ) const

返迴 true 若目前加載的後端支持 features .