Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_network_kernel_qnetworkinformation_reachability.cpp
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4//![file]
5#include <QCoreApplication>
6#include <QNetworkInformation>
7#include <QHostAddress>
8#include <QDebug>
9
10//! [0]
11// Simple helper to decide whether an IP address is "local"
12bool isLocalAddress(const QHostAddress &address)
13{
14 return address.isInSubnet(QHostAddress("192.168.0.0"), 16) ||
15 address.isInSubnet(QHostAddress("10.0.0.0"), 8) ||
16 address.isInSubnet(QHostAddress("172.16.0.0"), 12) ||
17 address.isLoopback();
18}
19
20
21int main(int argc, char *argv[])
22{
23//! [0]
24 QCoreApplication app(argc, argv);
25
26 // Load the default backend for QNetworkInformation
27 if (!QNetworkInformation::loadDefaultBackend()) {
28 qWarning() << "Failed to load QNetworkInformation backend. Exiting.";
29 return 1;
30 }
31
32 QNetworkInformation *networkInfo = QNetworkInformation::instance();
33//! [1]
34 // Target IP address (default: Google DNS)
35 QString targetIpStr = argc > 1 ? argv[1] : "8.8.8.8";
36 QHostAddress targetIp(targetIpStr);
37
38 if (targetIp.isNull()) {
39 qWarning() << "Invalid IP address:" << targetIpStr;
40 return 1;
41 }
42
43 // Decide what level of reachability is needed for the target
44 QNetworkInformation::Reachability requiredReachability =
45 isLocalAddress(targetIp)
46 ? QNetworkInformation::Reachability::Local
47 : QNetworkInformation::Reachability::Online;
48
49 // Fetch the current system-reported reachability
50 QNetworkInformation::Reachability currentReachability = networkInfo->reachability();
51
52 qDebug() << "Target IP:" << targetIp.toString();
53 qDebug() << "Target is considered"
54 << (isLocalAddress(targetIp) ? "local/site." : "external/online.");
55 qDebug() << "Required reachability level:" << requiredReachability;
56 qDebug() << "Current reachability:" << currentReachability;
57
58 if (currentReachability < requiredReachability) {
59 qWarning() << "Current network state may not allow reaching the target address.";
60 } else {
61 qDebug() << "Target may be reachable based on current network state.";
62 }
63//! [1]
64 return 0;
65}
66//![file]
int main(int argc, char *argv[])
[ctor_close]
bool isLocalAddress(const QHostAddress &address)
[file]