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
qnetworkinterface.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2017 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
8
9#include "qdebug.h"
10#include "qendian.h"
11#include "private/qtools_p.h"
12
13#ifndef QT_NO_NETWORKINTERFACE
14
16
17QT_IMPL_METATYPE_EXTERN(QNetworkAddressEntry)
18QT_IMPL_METATYPE_EXTERN(QNetworkInterface)
19
20static QList<QNetworkInterfacePrivate *> postProcess(QList<QNetworkInterfacePrivate *> list)
21{
22 // Some platforms report a netmask but don't report a broadcast address
23 // Go through all available addresses and calculate the broadcast address
24 // from the IP and the netmask
25 //
26 // This is an IPv4-only thing -- IPv6 has no concept of broadcasts
27 // The math is:
28 // broadcast = IP | ~netmask
29
30 for (QNetworkInterfacePrivate *iface : list) {
31 for (QNetworkAddressEntry &address : iface->addressEntries) {
32 if (address.ip().protocol() != QAbstractSocket::IPv4Protocol)
33 continue;
34
35 if (!address.netmask().isNull() && address.broadcast().isNull()) {
36 QHostAddress bcast = address.ip();
37 bcast = QHostAddress(bcast.toIPv4Address() | ~address.netmask().toIPv4Address());
38 address.setBroadcast(bcast);
39 }
40 }
41 }
42
43 return list;
44}
45
46Q_GLOBAL_STATIC(QNetworkInterfaceManager, manager)
47
48QNetworkInterfaceManager::QNetworkInterfaceManager()
49{
50}
51
55
56QSharedDataPointer<QNetworkInterfacePrivate> QNetworkInterfaceManager::interfaceFromName(const QString &name)
57{
58 const auto interfaceList = allInterfaces();
59
60 bool ok;
61 uint index = name.toUInt(&ok);
62
63 for (const auto &iface : interfaceList) {
64 if (ok && iface->index == int(index))
65 return iface;
66 else if (iface->name == name)
67 return iface;
68 }
69
70 return empty;
71}
72
74{
75 const auto interfaceList = allInterfaces();
76 for (const auto &iface : interfaceList) {
77 if (iface->index == index)
78 return iface;
79 }
80
81 return empty;
82}
83
85{
86 const QList<QNetworkInterfacePrivate *> list = postProcess(scan());
87 QList<QSharedDataPointer<QNetworkInterfacePrivate> > result;
88 result.reserve(list.size());
89
90 for (QNetworkInterfacePrivate *ptr : list) {
91 if ((ptr->flags & QNetworkInterface::IsUp) == 0) {
92 // if the network interface isn't UP, the addresses are ineligible for DNS
93 for (auto &addr : ptr->addressEntries)
94 addr.setDnsEligibility(QNetworkAddressEntry::DnsIneligible);
95 }
96
97 result << QSharedDataPointer<QNetworkInterfacePrivate>(ptr);
98 }
99
100 return result;
101}
102
103QString QNetworkInterfacePrivate::makeHwAddress(int len, uchar *data)
104{
105 const int outLen = qMax(len * 2 + (len - 1) * 1, 0);
106 QString result(outLen, Qt::Uninitialized);
107 QChar *out = result.data();
108 for (int i = 0; i < len; ++i) {
109 if (i)
110 *out++ = u':';
111 *out++ = QLatin1Char(QtMiscUtils::toHexUpper(data[i] / 16));
112 *out++ = QLatin1Char(QtMiscUtils::toHexUpper(data[i] % 16));
113 }
114 return result;
115}
116
117/*!
118 \class QNetworkAddressEntry
119 \brief The QNetworkAddressEntry class stores one IP address
120 supported by a network interface, along with its associated
121 netmask and broadcast address.
122
123 \since 4.2
124 \reentrant
125 \ingroup network
126 \ingroup shared
127 \inmodule QtNetwork
128
129 Each network interface can contain zero or more IP addresses, which
130 in turn can be associated with a netmask and/or a broadcast
131 address (depending on support from the operating system).
132
133 This class represents one such group.
134*/
135
136/*!
137 \enum QNetworkAddressEntry::DnsEligibilityStatus
138 \since 5.11
139
140 This enum indicates whether a given host address is eligible to be
141 published in the Domain Name System (DNS) or other similar name resolution
142 mechanisms. In general, an address is suitable for publication if it is an
143 address this machine will be reached at for an indeterminate amount of
144 time, though it need not be permanent. For example, addresses obtained via
145 DHCP are often eligible, but cryptographically-generated temporary IPv6
146 addresses are not.
147
148 \value DnsEligibilityUnknown Qt and the operating system could not determine
149 whether this address should be published or not.
150 The application may need to apply further
151 heuristics if it cannot find any eligible
152 addresses.
153 \value DnsEligible This address is eligible for publication in DNS.
154 \value DnsIneligible This address should not be published in DNS and
155 should not be transmitted to other parties,
156 except maybe as the source address of an outgoing
157 packet.
158
159 \sa dnsEligibility(), setDnsEligibility()
160*/
161
162/*!
163 Constructs an empty QNetworkAddressEntry object.
164*/
165QNetworkAddressEntry::QNetworkAddressEntry()
166 : d(new QNetworkAddressEntryPrivate)
167{
168}
169
170/*!
171 Constructs a QNetworkAddressEntry object that is a copy of the
172 object \a other.
173*/
174QNetworkAddressEntry::QNetworkAddressEntry(const QNetworkAddressEntry &other)
175 : d(new QNetworkAddressEntryPrivate(*other.d.get()))
176{
177}
178
179/*!
180 Makes a copy of the QNetworkAddressEntry object \a other.
181*/
182QNetworkAddressEntry &QNetworkAddressEntry::operator=(const QNetworkAddressEntry &other)
183{
184 *d.get() = *other.d.get();
185 return *this;
186}
187
188/*!
189 \fn void QNetworkAddressEntry::swap(QNetworkAddressEntry &other)
190 \since 5.0
191 \memberswap{network address entry instance}
192*/
193
194/*!
195 Destroys this QNetworkAddressEntry object.
196*/
197QNetworkAddressEntry::~QNetworkAddressEntry()
198{
199}
200
201/*!
202 Returns \c true if this network address entry is the same as \a
203 other.
204*/
205bool QNetworkAddressEntry::operator==(const QNetworkAddressEntry &other) const
206{
207 if (d == other.d) return true;
208 if (!d || !other.d) return false;
209 return d->address == other.d->address &&
210 d->netmask == other.d->netmask &&
211 d->broadcast == other.d->broadcast;
212}
213
214/*!
215 \since 5.11
216
217 Returns whether this address is eligible for publication in the Domain Name
218 System (DNS) or similar name resolution mechanisms.
219
220 In general, an address is suitable for publication if it is an address this
221 machine will be reached at for an indeterminate amount of time, though it
222 need not be permanent. For example, addresses obtained via DHCP are often
223 eligible, but cryptographically-generated temporary IPv6 addresses are not.
224
225 On some systems, QNetworkInterface will need to heuristically determine
226 which addresses are eligible.
227
228 \sa isLifetimeKnown(), isPermanent(), setDnsEligibility()
229*/
230QNetworkAddressEntry::DnsEligibilityStatus QNetworkAddressEntry::dnsEligibility() const
231{
232 return d->dnsEligibility;
233}
234
235/*!
236 \since 5.11
237
238 Sets the DNS eligibility flag for this address to \a status.
239
240 \sa dnsEligibility()
241*/
242void QNetworkAddressEntry::setDnsEligibility(DnsEligibilityStatus status)
243{
244 d->dnsEligibility = status;
245}
246
247/*!
248 \fn bool QNetworkAddressEntry::operator!=(const QNetworkAddressEntry &other) const
249
250 Returns \c true if this network address entry is different from \a
251 other.
252*/
253
254/*!
255 This function returns one IPv4 or IPv6 address found, that was
256 found in a network interface.
257*/
258QHostAddress QNetworkAddressEntry::ip() const
259{
260 return d->address;
261}
262
263/*!
264 Sets the IP address the QNetworkAddressEntry object contains to \a
265 newIp.
266*/
267void QNetworkAddressEntry::setIp(const QHostAddress &newIp)
268{
269 d->address = newIp;
270}
271
272/*!
273 Returns the netmask associated with the IP address. The
274 netmask is expressed in the form of an IP address, such as
275 255.255.0.0.
276
277 For IPv6 addresses, the prefix length is converted to an address
278 where the number of bits set to 1 is equal to the prefix
279 length. For a prefix length of 64 bits (the most common value),
280 the netmask will be expressed as a QHostAddress holding the
281 address FFFF:FFFF:FFFF:FFFF::
282
283 \sa prefixLength()
284*/
285QHostAddress QNetworkAddressEntry::netmask() const
286{
287 return d->netmask.address(d->address.protocol());
288}
289
290/*!
291 Sets the netmask that this QNetworkAddressEntry object contains to
292 \a newNetmask. Setting the netmask also sets the prefix length to
293 match the new netmask.
294
295 \sa setPrefixLength()
296*/
297void QNetworkAddressEntry::setNetmask(const QHostAddress &newNetmask)
298{
299 if (newNetmask.protocol() != ip().protocol()) {
300 d->netmask = QNetmask();
301 return;
302 }
303
304 d->netmask.setAddress(newNetmask);
305}
306
307/*!
308 \since 4.5
309 Returns the prefix length of this IP address. The prefix length
310 matches the number of bits set to 1 in the netmask (see
311 netmask()). For IPv4 addresses, the value is between 0 and 32. For
312 IPv6 addresses, it's contained between 0 and 128 and is the
313 preferred form of representing addresses.
314
315 This function returns -1 if the prefix length could not be
316 determined (i.e., netmask() returns a null QHostAddress()).
317
318 \sa netmask()
319*/
320int QNetworkAddressEntry::prefixLength() const
321{
322 return d->netmask.prefixLength();
323}
324
325/*!
326 \since 4.5
327 Sets the prefix length of this IP address to \a length. The value
328 of \a length must be valid for this type of IP address: between 0
329 and 32 for IPv4 addresses, between 0 and 128 for IPv6
330 addresses. Setting to any invalid value is equivalent to setting
331 to -1, which means "no prefix length".
332
333 Setting the prefix length also sets the netmask (see netmask()).
334
335 \sa setNetmask()
336*/
337void QNetworkAddressEntry::setPrefixLength(int length)
338{
339 d->netmask.setPrefixLength(d->address.protocol(), length);
340}
341
342/*!
343 Returns the broadcast address associated with the IPv4
344 address and netmask. It can usually be derived from those two by
345 setting to 1 the bits of the IP address where the netmask contains
346 a 0. (In other words, by bitwise-OR'ing the IP address with the
347 inverse of the netmask)
348
349 This member is always empty for IPv6 addresses, since the concept
350 of broadcast has been abandoned in that system in favor of
351 multicast. In particular, the group of hosts corresponding to all
352 the nodes in the local network can be reached by the "all-nodes"
353 special multicast group (address FF02::1).
354*/
355QHostAddress QNetworkAddressEntry::broadcast() const
356{
357 return d->broadcast;
358}
359
360/*!
361 Sets the broadcast IP address of this QNetworkAddressEntry object
362 to \a newBroadcast.
363*/
364void QNetworkAddressEntry::setBroadcast(const QHostAddress &newBroadcast)
365{
366 d->broadcast = newBroadcast;
367}
368
369/*!
370 \since 5.11
371
372 Returns \c true if the address lifetime is known, \c false if not. If the
373 lifetime is not known, both preferredLifetime() and validityLifetime() will
374 return QDeadlineTimer::Forever.
375
376 \sa preferredLifetime(), validityLifetime(), setAddressLifetime(), clearAddressLifetime()
377*/
378bool QNetworkAddressEntry::isLifetimeKnown() const
379{
380 return d->lifetimeKnown;
381}
382
383/*!
384 \since 5.11
385
386 Returns the deadline when this address becomes deprecated (no longer
387 preferred), if known. If the address lifetime is not known (see
388 isLifetimeKnown()), this function always returns QDeadlineTimer::Forever.
389
390 While an address is preferred, it may be used by the operating system as
391 the source address for new, outgoing packets. After it becomes deprecated,
392 it will remain valid for incoming packets for a while longer until finally
393 removed (see validityLifetime()).
394
395 \sa validityLifetime(), isLifetimeKnown(), setAddressLifetime(), clearAddressLifetime()
396*/
397QDeadlineTimer QNetworkAddressEntry::preferredLifetime() const
398{
399 return d->preferredLifetime;
400}
401
402/*!
403 \since 5.11
404
405 Returns the deadline when this address becomes invalid and will be removed
406 from the networking stack, if known. If the address lifetime is not known
407 (see isLifetimeKnown()), this function always returns
408 QDeadlineTimer::Forever.
409
410 While an address is valid, it will be accepted by the operating system as a
411 valid destination address for this machine. Whether it is used as a source
412 address for new, outgoing packets is controlled by, among other rules, the
413 preferred lifetime (see preferredLifetime()).
414
415 \sa preferredLifetime(), isLifetimeKnown(), setAddressLifetime(), clearAddressLifetime()
416*/
417QDeadlineTimer QNetworkAddressEntry::validityLifetime() const
418{
419 return d->validityLifetime;
420}
421
422/*!
423 \since 5.11
424
425 Sets both the preferred and valid lifetimes for this address to the \a
426 preferred and \a validity deadlines, respectively. After this call,
427 isLifetimeKnown() will return \c true, even if both parameters are
428 QDeadlineTimer::Forever.
429
430 \sa preferredLifetime(), validityLifetime(), isLifetimeKnown(), clearAddressLifetime()
431*/
432void QNetworkAddressEntry::setAddressLifetime(QDeadlineTimer preferred, QDeadlineTimer validity)
433{
434 d->preferredLifetime = preferred;
435 d->validityLifetime = validity;
436 d->lifetimeKnown = true;
437}
438
439/*!
440 \since 5.11
441
442 Resets both the preferred and valid lifetimes for this address. After this
443 call, isLifetimeKnown() will return \c false.
444
445 \sa preferredLifetime(), validityLifetime(), isLifetimeKnown(), setAddressLifetime()
446*/
447void QNetworkAddressEntry::clearAddressLifetime()
448{
449 d->preferredLifetime = QDeadlineTimer::Forever;
450 d->validityLifetime = QDeadlineTimer::Forever;
451 d->lifetimeKnown = false;
452}
453
454/*!
455 \since 5.11
456
457 Returns \c true if this address is permanent on this interface, \c false if
458 it's temporary. A permanent address is one which has no expiration time and
459 is often static (manually configured).
460
461 If this information could not be determined, this function returns \c true.
462
463 \note Depending on the operating system and the networking configuration
464 tool, it is possible for a temporary address to be interpreted as
465 permanent, if the tool did not inform the details correctly to the
466 operating system.
467
468 \sa isLifetimeKnown(), validityLifetime(), isTemporary()
469*/
470bool QNetworkAddressEntry::isPermanent() const
471{
472 return d->validityLifetime.isForever();
473}
474
475/*!
476 \fn bool QNetworkAddressEntry::isTemporary() const
477 \since 5.11
478
479 Returns \c true if this address is temporary on this interface, \c false if
480 it's permanent.
481
482 \sa isLifetimeKnown(), validityLifetime(), isPermanent()
483*/
484
485/*!
486 \class QNetworkInterface
487 \brief The QNetworkInterface class provides a listing of the host's IP
488 addresses and network interfaces.
489
490 \since 4.2
491 \reentrant
492 \ingroup network
493 \ingroup shared
494 \inmodule QtNetwork
495
496 QNetworkInterface represents one network interface attached to the
497 host where the program is being run. Each network interface may
498 contain zero or more IP addresses, each of which is optionally
499 associated with a netmask and/or a broadcast address. The list of
500 such trios can be obtained with addressEntries(). Alternatively,
501 when the netmask or the broadcast addresses or other information aren't
502 necessary, use the allAddresses() convenience function to obtain just the
503 IP addresses of the active interfaces.
504
505 QNetworkInterface also reports the interface's hardware address with
506 hardwareAddress().
507
508 Not all operating systems support reporting all features. Only the
509 IPv4 addresses are guaranteed to be listed by this class in all
510 platforms. In particular, IPv6 address listing is only supported
511 on Windows, Linux, \macos and the BSDs. Similarly, the interface
512 type reported by type() may not be available on all platforms.
513
514 \note On Android, the interface type is always reported as \l Unknown,
515 as the platform does not expose hardware type information for physical
516 interfaces.
517
518 \sa QNetworkAddressEntry
519*/
520
521/*!
522 \enum QNetworkInterface::InterfaceFlag
523 Specifies the flags associated with this network interface. The
524 possible values are:
525
526 \value IsUp the network interface is "up" -
527 enabled by administrative action
528 \value IsRunning the network interface is operational:
529 configured "up" and (typically)
530 physically connected to a network
531 \value CanBroadcast the network interface works in
532 broadcast mode
533 \value IsLoopBack the network interface is a loopback
534 interface: that is, it's a virtual
535 interface whose destination is the
536 host computer itself
537 \value IsPointToPoint the network interface is a
538 point-to-point interface: that is,
539 there is one, single other address
540 that can be directly reached by it.
541 \value CanMulticast the network interface supports
542 multicasting
543
544 Note that one network interface cannot be both broadcast-based and
545 point-to-point.
546*/
547
548/*!
549 \enum QNetworkInterface::InterfaceType
550
551 Specifies the type of hardware (PHY layer, OSI level 1) this interface is,
552 if it could be determined. Interface types that are not among those listed
553 below will generally be listed as Unknown, though future versions of Qt may
554 add new enumeration values.
555
556 The possible values are:
557
558 \value Unknown The interface type could not be determined or is not
559 one of the other listed types.
560 \value Loopback The virtual loopback interface, which is assigned
561 the loopback IP addresses (127.0.0.1, ::1).
562 \value Virtual A type of interface determined to be virtual, but
563 not any of the other possible types. For example,
564 tunnel interfaces are (currently) detected as
565 virtual ones.
566 \value Ethernet IEEE 802.3 Ethernet interfaces, though on many
567 systems other types of IEEE 802 interfaces may also
568 be detected as Ethernet (especially Wi-Fi).
569 \value Wifi IEEE 802.11 Wi-Fi interfaces. Note that on some
570 systems, QNetworkInterface may be unable to
571 distinguish regular Ethernet from Wi-Fi and will
572 not return this enum value.
573 \value Ieee80211 An alias for WiFi.
574 \value CanBus ISO 11898 Controller Area Network bus interfaces,
575 usually found on automotive systems.
576 \value Fddi ANSI X3T12 Fiber Distributed Data Interface, a local area
577 network over optical fibers.
578 \value Ppp Point-to-Point Protocol interfaces, establishing a
579 direct connection between two nodes over a lower
580 transport layer (often serial over radio or physical
581 line).
582 \value Slip Serial Line Internet Protocol interfaces.
583 \value Phonet Interfaces using the Linux Phonet socket family, for
584 communication with cellular modems. See the
585 \l {https://www.kernel.org/doc/Documentation/networking/phonet.txt}{Linux kernel documentation}
586 for more information.
587 \value Ieee802154 IEEE 802.15.4 Personal Area Network interfaces, other
588 than 6LoWPAN (see below).
589 \value SixLoWPAN 6LoWPAN (IPv6 over Low-power Wireless Personal Area
590 Networks) interfaces, which operate on IEEE 802.15.4
591 PHY, but have specific header compression schemes
592 for IPv6 and UDP. This type of interface is often
593 used for mesh networking.
594 \value Ieee80216 IEEE 802.16 Wireless Metropolitan Area Network, also
595 known under the commercial name "WiMAX".
596 \value Ieee1394 IEEE 1394 interfaces (a.k.a. "FireWire").
597*/
598
599/*!
600 Constructs an empty network interface object.
601*/
602QNetworkInterface::QNetworkInterface()
603 : d(nullptr)
604{
605}
606
607/*!
608 Frees the resources associated with the QNetworkInterface object.
609*/
610QNetworkInterface::~QNetworkInterface()
611{
612}
613
614/*!
615 Creates a copy of the QNetworkInterface object contained in \a
616 other.
617*/
618QNetworkInterface::QNetworkInterface(const QNetworkInterface &other)
619 : d(other.d)
620{
621}
622
623/*!
624 Copies the contents of the QNetworkInterface object contained in \a
625 other into this one.
626*/
627QNetworkInterface &QNetworkInterface::operator=(const QNetworkInterface &other)
628{
629 d = other.d;
630 return *this;
631}
632
633/*!
634 \fn void QNetworkInterface::swap(QNetworkInterface &other)
635 \since 5.0
636 \memberswap{network interface instance}
637*/
638
639/*!
640 Returns \c true if this QNetworkInterface object contains valid
641 information about a network interface.
642*/
643bool QNetworkInterface::isValid() const
644{
645 return !name().isEmpty();
646}
647
648/*!
649 \since 4.5
650 Returns the interface system index, if known. This is an integer
651 assigned by the operating system to identify this interface and it
652 generally doesn't change. It matches the scope ID field in IPv6
653 addresses.
654
655 If the index isn't known, this function returns 0.
656*/
657int QNetworkInterface::index() const
658{
659 return d ? d->index : 0;
660}
661
662/*!
663 \since 5.11
664
665 Returns the maximum transmission unit on this interface, if known, or 0
666 otherwise.
667
668 The maximum transmission unit is the largest packet that may be sent on
669 this interface without incurring link-level fragmentation. Applications may
670 use this value to calculate the size of the payload that will fit an
671 unfragmented UDP datagram. Remember to subtract the sizes of headers used
672 in your communication over the interface, e.g. TCP (20 bytes) or UDP (12),
673 IPv4 (20) or IPv6 (40, absent some form of header compression), when
674 computing how big a payload you can transmit. Also note that the MTU along
675 the full path (the Path MTU) to the destination may be smaller than the
676 interface's MTU.
677
678 \sa QUdpSocket
679*/
680int QNetworkInterface::maximumTransmissionUnit() const
681{
682 return d ? d->mtu : 0;
683}
684
685/*!
686 Returns the name of this network interface. On Unix systems, this
687 is a string containing the type of the interface and optionally a
688 sequence number, such as "eth0", "lo" or "pcn0". On Windows, it's
689 an internal ID that cannot be changed by the user.
690*/
691QString QNetworkInterface::name() const
692{
693 return d ? d->name : QString();
694}
695
696/*!
697 \since 4.5
698
699 Returns the human-readable name of this network interface on
700 Windows, such as "Local Area Connection", if the name could be
701 determined. If it couldn't, this function returns the same as
702 name(). The human-readable name is a name that the user can modify
703 in the Windows Control Panel, so it may change during the
704 execution of the program.
705
706 On Unix, this function currently always returns the same as
707 name(), since Unix systems don't store a configuration for
708 human-readable names.
709*/
710QString QNetworkInterface::humanReadableName() const
711{
712 return d ? !d->friendlyName.isEmpty() ? d->friendlyName : name() : QString();
713}
714
715/*!
716 Returns the flags associated with this network interface.
717*/
718QNetworkInterface::InterfaceFlags QNetworkInterface::flags() const
719{
720 return d ? d->flags : InterfaceFlags{};
721}
722
723/*!
724 \since 5.11
725
726 Returns the type of this interface, if it could be determined. If it could
727 not be determined, this function returns QNetworkInterface::Unknown.
728
729 \sa hardwareAddress()
730*/
731QNetworkInterface::InterfaceType QNetworkInterface::type() const
732{
733 return d ? d->type : Unknown;
734}
735
736/*!
737 Returns the low-level hardware address for this interface. On
738 Ethernet interfaces, this will be a MAC address in string
739 representation, separated by colons.
740
741 Other interface types may have other types of hardware
742 addresses. Implementations should not depend on this function
743 returning a valid MAC address.
744
745 \sa type()
746*/
747QString QNetworkInterface::hardwareAddress() const
748{
749 return d ? d->hardwareAddress : QString();
750}
751
752/*!
753 Returns the list of IP addresses that this interface possesses
754 along with their associated netmasks and broadcast addresses.
755
756 If the netmask or broadcast address or other information is not necessary,
757 you can call the allAddresses() function to obtain just the IP addresses of
758 the active interfaces.
759*/
760QList<QNetworkAddressEntry> QNetworkInterface::addressEntries() const
761{
762 return d ? d->addressEntries : QList<QNetworkAddressEntry>();
763}
764
765/*!
766 \since 5.7
767
768 Returns the index of the interface whose name is \a name or 0 if there is
769 no interface with that name. This function should produce the same result
770 as the following code, but will probably execute faster.
771
772 \snippet code/src_network_kernel_qnetworkinterface.cpp 0
773
774 \sa interfaceFromName(), interfaceNameFromIndex(), QNetworkDatagram::interfaceIndex()
775*/
776int QNetworkInterface::interfaceIndexFromName(const QString &name)
777{
778 if (name.isEmpty())
779 return 0;
780
781 bool ok;
782 uint id = name.toUInt(&ok);
783 if (!ok)
784 id = QNetworkInterfaceManager::interfaceIndexFromName(name);
785 return int(id);
786}
787
788/*!
789 Returns a QNetworkInterface object for the interface named \a
790 name. If no such interface exists, this function returns an
791 invalid QNetworkInterface object.
792
793 The string \a name may be either an actual interface name (such as "eth0"
794 or "en1") or an interface index in string form ("1", "2", etc.).
795
796 \sa name(), isValid()
797*/
798QNetworkInterface QNetworkInterface::interfaceFromName(const QString &name)
799{
800 QNetworkInterface result;
801 result.d = manager()->interfaceFromName(name);
802 return result;
803}
804
805/*!
806 Returns a QNetworkInterface object for the interface whose internal
807 ID is \a index. Network interfaces have a unique identifier called
808 the "interface index" to distinguish it from other interfaces on
809 the system. Often, this value is assigned progressively and
810 interfaces being removed and then added again get a different
811 value every time.
812
813 This index is also found in the IPv6 address' scope ID field.
814*/
815QNetworkInterface QNetworkInterface::interfaceFromIndex(int index)
816{
817 QNetworkInterface result;
818 result.d = manager()->interfaceFromIndex(index);
819 return result;
820}
821
822/*!
823 \since 5.7
824
825 Returns the name of the interface whose index is \a index or an empty
826 string if there is no interface with that index. This function should
827 produce the same result as the following code, but will probably execute
828 faster.
829
830 \snippet code/src_network_kernel_qnetworkinterface.cpp 1
831
832 \sa interfaceFromIndex(), interfaceIndexFromName(), QNetworkDatagram::interfaceIndex()
833*/
834QString QNetworkInterface::interfaceNameFromIndex(int index)
835{
836 if (!index)
837 return QString();
838 return QNetworkInterfaceManager::interfaceNameFromIndex(index);
839}
840
841/*!
842 Returns a listing of all the network interfaces found on the host
843 machine. In case of failure it returns a list with zero elements.
844*/
845QList<QNetworkInterface> QNetworkInterface::allInterfaces()
846{
847 const QList<QSharedDataPointer<QNetworkInterfacePrivate> > privs = manager()->allInterfaces();
848 QList<QNetworkInterface> result;
849 result.reserve(privs.size());
850 for (const auto &p : privs) {
851 QNetworkInterface item;
852 item.d = p;
853 result << item;
854 }
855
856 return result;
857}
858
859/*!
860 This convenience function returns all IP addresses found on the host
861 machine. It is equivalent to calling addressEntries() on all the objects
862 returned by allInterfaces() that are in the QNetworkInterface::IsUp state
863 to obtain lists of QNetworkAddressEntry objects then calling
864 QNetworkAddressEntry::ip() on each of these.
865*/
866QList<QHostAddress> QNetworkInterface::allAddresses()
867{
868 const QList<QSharedDataPointer<QNetworkInterfacePrivate> > privs = manager()->allInterfaces();
869 QList<QHostAddress> result;
870 for (const auto &p : privs) {
871 // skip addresses if the interface isn't up
872 if ((p->flags & QNetworkInterface::IsUp) == 0)
873 continue;
874
875 for (const QNetworkAddressEntry &entry : std::as_const(p->addressEntries))
876 result += entry.ip();
877 }
878
879 return result;
880}
881
882#ifndef QT_NO_DEBUG_STREAM
883static inline QDebug flagsDebug(QDebug debug, QNetworkInterface::InterfaceFlags flags)
884{
885 if (flags & QNetworkInterface::IsUp)
886 debug << "IsUp ";
887 if (flags & QNetworkInterface::IsRunning)
888 debug << "IsRunning ";
889 if (flags & QNetworkInterface::CanBroadcast)
890 debug << "CanBroadcast ";
891 if (flags & QNetworkInterface::IsLoopBack)
892 debug << "IsLoopBack ";
893 if (flags & QNetworkInterface::IsPointToPoint)
894 debug << "IsPointToPoint ";
895 if (flags & QNetworkInterface::CanMulticast)
896 debug << "CanMulticast ";
897 return debug;
898}
899
900/*!
901 \since 6.2
902
903 Writes the QNetworkAddressEntry \a entry to the stream and
904 returns a reference to the \a debug stream.
905
906 \relates QNetworkAddressEntry
907 */
908QDebug operator<<(QDebug debug, const QNetworkAddressEntry &entry)
909{
910 QDebugStateSaver saver(debug);
911 debug.resetFormat().nospace();
912 debug << "address = " << entry.ip();
913 if (!entry.netmask().isNull())
914 debug << ", netmask = " << entry.netmask();
915 if (!entry.broadcast().isNull())
916 debug << ", broadcast = " << entry.broadcast();
917 return debug;
918}
919
920/*!
921 Writes the QNetworkInterface \a networkInterface to the stream and
922 returns a reference to the \a debug stream.
923
924 \relates QNetworkInterface
925 */
926QDebug operator<<(QDebug debug, const QNetworkInterface &networkInterface)
927{
928 QDebugStateSaver saver(debug);
929 debug.resetFormat().nospace();
930 debug << "QNetworkInterface(name = " << networkInterface.name()
931 << ", hardware address = " << networkInterface.hardwareAddress()
932 << ", flags = ";
933 flagsDebug(debug, networkInterface.flags());
934 debug << ", entries = " << networkInterface.addressEntries()
935 << ")\n";
936 return debug;
937}
938#endif
939
940QT_END_NAMESPACE
941
942#include "moc_qnetworkinterface.cpp"
943
944#endif // QT_NO_NETWORKINTERFACE
QList< QSharedDataPointer< QNetworkInterfacePrivate > > allInterfaces()
QSharedDataPointer< QNetworkInterfacePrivate > interfaceFromIndex(int index)
Combined button and popup list for selecting options.
QDebug operator<<(QDebug dbg, const QFileInfo &fi)
static QDebug flagsDebug(QDebug debug, QNetworkInterface::InterfaceFlags flags)