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
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.
512
513 \sa QNetworkAddressEntry
514*/
515
516/*!
517 \enum QNetworkInterface::InterfaceFlag
518 Specifies the flags associated with this network interface. The
519 possible values are:
520
521 \value IsUp the network interface is "up" -
522 enabled by administrative action
523 \value IsRunning the network interface is operational:
524 configured "up" and (typically)
525 physically connected to a network
526 \value CanBroadcast the network interface works in
527 broadcast mode
528 \value IsLoopBack the network interface is a loopback
529 interface: that is, it's a virtual
530 interface whose destination is the
531 host computer itself
532 \value IsPointToPoint the network interface is a
533 point-to-point interface: that is,
534 there is one, single other address
535 that can be directly reached by it.
536 \value CanMulticast the network interface supports
537 multicasting
538
539 Note that one network interface cannot be both broadcast-based and
540 point-to-point.
541*/
542
543/*!
544 \enum QNetworkInterface::InterfaceType
545
546 Specifies the type of hardware (PHY layer, OSI level 1) this interface is,
547 if it could be determined. Interface types that are not among those listed
548 below will generally be listed as Unknown, though future versions of Qt may
549 add new enumeration values.
550
551 The possible values are:
552
553 \value Unknown The interface type could not be determined or is not
554 one of the other listed types.
555 \value Loopback The virtual loopback interface, which is assigned
556 the loopback IP addresses (127.0.0.1, ::1).
557 \value Virtual A type of interface determined to be virtual, but
558 not any of the other possible types. For example,
559 tunnel interfaces are (currently) detected as
560 virtual ones.
561 \value Ethernet IEEE 802.3 Ethernet interfaces, though on many
562 systems other types of IEEE 802 interfaces may also
563 be detected as Ethernet (especially Wi-Fi).
564 \value Wifi IEEE 802.11 Wi-Fi interfaces. Note that on some
565 systems, QNetworkInterface may be unable to
566 distinguish regular Ethernet from Wi-Fi and will
567 not return this enum value.
568 \value Ieee80211 An alias for WiFi.
569 \value CanBus ISO 11898 Controller Area Network bus interfaces,
570 usually found on automotive systems.
571 \value Fddi ANSI X3T12 Fiber Distributed Data Interface, a local area
572 network over optical fibers.
573 \value Ppp Point-to-Point Protocol interfaces, establishing a
574 direct connection between two nodes over a lower
575 transport layer (often serial over radio or physical
576 line).
577 \value Slip Serial Line Internet Protocol interfaces.
578 \value Phonet Interfaces using the Linux Phonet socket family, for
579 communication with cellular modems. See the
580 \l {https://www.kernel.org/doc/Documentation/networking/phonet.txt}{Linux kernel documentation}
581 for more information.
582 \value Ieee802154 IEEE 802.15.4 Personal Area Network interfaces, other
583 than 6LoWPAN (see below).
584 \value SixLoWPAN 6LoWPAN (IPv6 over Low-power Wireless Personal Area
585 Networks) interfaces, which operate on IEEE 802.15.4
586 PHY, but have specific header compression schemes
587 for IPv6 and UDP. This type of interface is often
588 used for mesh networking.
589 \value Ieee80216 IEEE 802.16 Wireless Metropolitan Area Network, also
590 known under the commercial name "WiMAX".
591 \value Ieee1394 IEEE 1394 interfaces (a.k.a. "FireWire").
592*/
593
594/*!
595 Constructs an empty network interface object.
596*/
597QNetworkInterface::QNetworkInterface()
598 : d(nullptr)
599{
600}
601
602/*!
603 Frees the resources associated with the QNetworkInterface object.
604*/
605QNetworkInterface::~QNetworkInterface()
606{
607}
608
609/*!
610 Creates a copy of the QNetworkInterface object contained in \a
611 other.
612*/
613QNetworkInterface::QNetworkInterface(const QNetworkInterface &other)
614 : d(other.d)
615{
616}
617
618/*!
619 Copies the contents of the QNetworkInterface object contained in \a
620 other into this one.
621*/
622QNetworkInterface &QNetworkInterface::operator=(const QNetworkInterface &other)
623{
624 d = other.d;
625 return *this;
626}
627
628/*!
629 \fn void QNetworkInterface::swap(QNetworkInterface &other)
630 \since 5.0
631 \memberswap{network interface instance}
632*/
633
634/*!
635 Returns \c true if this QNetworkInterface object contains valid
636 information about a network interface.
637*/
638bool QNetworkInterface::isValid() const
639{
640 return !name().isEmpty();
641}
642
643/*!
644 \since 4.5
645 Returns the interface system index, if known. This is an integer
646 assigned by the operating system to identify this interface and it
647 generally doesn't change. It matches the scope ID field in IPv6
648 addresses.
649
650 If the index isn't known, this function returns 0.
651*/
652int QNetworkInterface::index() const
653{
654 return d ? d->index : 0;
655}
656
657/*!
658 \since 5.11
659
660 Returns the maximum transmission unit on this interface, if known, or 0
661 otherwise.
662
663 The maximum transmission unit is the largest packet that may be sent on
664 this interface without incurring link-level fragmentation. Applications may
665 use this value to calculate the size of the payload that will fit an
666 unfragmented UDP datagram. Remember to subtract the sizes of headers used
667 in your communication over the interface, e.g. TCP (20 bytes) or UDP (12),
668 IPv4 (20) or IPv6 (40, absent some form of header compression), when
669 computing how big a payload you can transmit. Also note that the MTU along
670 the full path (the Path MTU) to the destination may be smaller than the
671 interface's MTU.
672
673 \sa QUdpSocket
674*/
675int QNetworkInterface::maximumTransmissionUnit() const
676{
677 return d ? d->mtu : 0;
678}
679
680/*!
681 Returns the name of this network interface. On Unix systems, this
682 is a string containing the type of the interface and optionally a
683 sequence number, such as "eth0", "lo" or "pcn0". On Windows, it's
684 an internal ID that cannot be changed by the user.
685*/
686QString QNetworkInterface::name() const
687{
688 return d ? d->name : QString();
689}
690
691/*!
692 \since 4.5
693
694 Returns the human-readable name of this network interface on
695 Windows, such as "Local Area Connection", if the name could be
696 determined. If it couldn't, this function returns the same as
697 name(). The human-readable name is a name that the user can modify
698 in the Windows Control Panel, so it may change during the
699 execution of the program.
700
701 On Unix, this function currently always returns the same as
702 name(), since Unix systems don't store a configuration for
703 human-readable names.
704*/
705QString QNetworkInterface::humanReadableName() const
706{
707 return d ? !d->friendlyName.isEmpty() ? d->friendlyName : name() : QString();
708}
709
710/*!
711 Returns the flags associated with this network interface.
712*/
713QNetworkInterface::InterfaceFlags QNetworkInterface::flags() const
714{
715 return d ? d->flags : InterfaceFlags{};
716}
717
718/*!
719 \since 5.11
720
721 Returns the type of this interface, if it could be determined. If it could
722 not be determined, this function returns QNetworkInterface::Unknown.
723
724 \sa hardwareAddress()
725*/
726QNetworkInterface::InterfaceType QNetworkInterface::type() const
727{
728 return d ? d->type : Unknown;
729}
730
731/*!
732 Returns the low-level hardware address for this interface. On
733 Ethernet interfaces, this will be a MAC address in string
734 representation, separated by colons.
735
736 Other interface types may have other types of hardware
737 addresses. Implementations should not depend on this function
738 returning a valid MAC address.
739
740 \sa type()
741*/
742QString QNetworkInterface::hardwareAddress() const
743{
744 return d ? d->hardwareAddress : QString();
745}
746
747/*!
748 Returns the list of IP addresses that this interface possesses
749 along with their associated netmasks and broadcast addresses.
750
751 If the netmask or broadcast address or other information is not necessary,
752 you can call the allAddresses() function to obtain just the IP addresses of
753 the active interfaces.
754*/
755QList<QNetworkAddressEntry> QNetworkInterface::addressEntries() const
756{
757 return d ? d->addressEntries : QList<QNetworkAddressEntry>();
758}
759
760/*!
761 \since 5.7
762
763 Returns the index of the interface whose name is \a name or 0 if there is
764 no interface with that name. This function should produce the same result
765 as the following code, but will probably execute faster.
766
767 \snippet code/src_network_kernel_qnetworkinterface.cpp 0
768
769 \sa interfaceFromName(), interfaceNameFromIndex(), QNetworkDatagram::interfaceIndex()
770*/
771int QNetworkInterface::interfaceIndexFromName(const QString &name)
772{
773 if (name.isEmpty())
774 return 0;
775
776 bool ok;
777 uint id = name.toUInt(&ok);
778 if (!ok)
779 id = QNetworkInterfaceManager::interfaceIndexFromName(name);
780 return int(id);
781}
782
783/*!
784 Returns a QNetworkInterface object for the interface named \a
785 name. If no such interface exists, this function returns an
786 invalid QNetworkInterface object.
787
788 The string \a name may be either an actual interface name (such as "eth0"
789 or "en1") or an interface index in string form ("1", "2", etc.).
790
791 \sa name(), isValid()
792*/
793QNetworkInterface QNetworkInterface::interfaceFromName(const QString &name)
794{
795 QNetworkInterface result;
796 result.d = manager()->interfaceFromName(name);
797 return result;
798}
799
800/*!
801 Returns a QNetworkInterface object for the interface whose internal
802 ID is \a index. Network interfaces have a unique identifier called
803 the "interface index" to distinguish it from other interfaces on
804 the system. Often, this value is assigned progressively and
805 interfaces being removed and then added again get a different
806 value every time.
807
808 This index is also found in the IPv6 address' scope ID field.
809*/
810QNetworkInterface QNetworkInterface::interfaceFromIndex(int index)
811{
812 QNetworkInterface result;
813 result.d = manager()->interfaceFromIndex(index);
814 return result;
815}
816
817/*!
818 \since 5.7
819
820 Returns the name of the interface whose index is \a index or an empty
821 string if there is no interface with that index. This function should
822 produce the same result as the following code, but will probably execute
823 faster.
824
825 \snippet code/src_network_kernel_qnetworkinterface.cpp 1
826
827 \sa interfaceFromIndex(), interfaceIndexFromName(), QNetworkDatagram::interfaceIndex()
828*/
829QString QNetworkInterface::interfaceNameFromIndex(int index)
830{
831 if (!index)
832 return QString();
833 return QNetworkInterfaceManager::interfaceNameFromIndex(index);
834}
835
836/*!
837 Returns a listing of all the network interfaces found on the host
838 machine. In case of failure it returns a list with zero elements.
839*/
840QList<QNetworkInterface> QNetworkInterface::allInterfaces()
841{
842 const QList<QSharedDataPointer<QNetworkInterfacePrivate> > privs = manager()->allInterfaces();
843 QList<QNetworkInterface> result;
844 result.reserve(privs.size());
845 for (const auto &p : privs) {
846 QNetworkInterface item;
847 item.d = p;
848 result << item;
849 }
850
851 return result;
852}
853
854/*!
855 This convenience function returns all IP addresses found on the host
856 machine. It is equivalent to calling addressEntries() on all the objects
857 returned by allInterfaces() that are in the QNetworkInterface::IsUp state
858 to obtain lists of QNetworkAddressEntry objects then calling
859 QNetworkAddressEntry::ip() on each of these.
860*/
861QList<QHostAddress> QNetworkInterface::allAddresses()
862{
863 const QList<QSharedDataPointer<QNetworkInterfacePrivate> > privs = manager()->allInterfaces();
864 QList<QHostAddress> result;
865 for (const auto &p : privs) {
866 // skip addresses if the interface isn't up
867 if ((p->flags & QNetworkInterface::IsUp) == 0)
868 continue;
869
870 for (const QNetworkAddressEntry &entry : std::as_const(p->addressEntries))
871 result += entry.ip();
872 }
873
874 return result;
875}
876
877#ifndef QT_NO_DEBUG_STREAM
878static inline QDebug flagsDebug(QDebug debug, QNetworkInterface::InterfaceFlags flags)
879{
880 if (flags & QNetworkInterface::IsUp)
881 debug << "IsUp ";
882 if (flags & QNetworkInterface::IsRunning)
883 debug << "IsRunning ";
884 if (flags & QNetworkInterface::CanBroadcast)
885 debug << "CanBroadcast ";
886 if (flags & QNetworkInterface::IsLoopBack)
887 debug << "IsLoopBack ";
888 if (flags & QNetworkInterface::IsPointToPoint)
889 debug << "IsPointToPoint ";
890 if (flags & QNetworkInterface::CanMulticast)
891 debug << "CanMulticast ";
892 return debug;
893}
894
895/*!
896 \since 6.2
897
898 Writes the QNetworkAddressEntry \a entry to the stream and
899 returns a reference to the \a debug stream.
900
901 \relates QNetworkAddressEntry
902 */
903QDebug operator<<(QDebug debug, const QNetworkAddressEntry &entry)
904{
905 QDebugStateSaver saver(debug);
906 debug.resetFormat().nospace();
907 debug << "address = " << entry.ip();
908 if (!entry.netmask().isNull())
909 debug << ", netmask = " << entry.netmask();
910 if (!entry.broadcast().isNull())
911 debug << ", broadcast = " << entry.broadcast();
912 return debug;
913}
914
915/*!
916 Writes the QNetworkInterface \a networkInterface to the stream and
917 returns a reference to the \a debug stream.
918
919 \relates QNetworkInterface
920 */
921QDebug operator<<(QDebug debug, const QNetworkInterface &networkInterface)
922{
923 QDebugStateSaver saver(debug);
924 debug.resetFormat().nospace();
925 debug << "QNetworkInterface(name = " << networkInterface.name()
926 << ", hardware address = " << networkInterface.hardwareAddress()
927 << ", flags = ";
928 flagsDebug(debug, networkInterface.flags());
929 debug << ", entries = " << networkInterface.addressEntries()
930 << ")\n";
931 return debug;
932}
933#endif
934
935QT_END_NAMESPACE
936
937#include "moc_qnetworkinterface.cpp"
938
939#endif // QT_NO_NETWORKINTERFACE
QSharedDataPointer< QNetworkInterfacePrivate > interfaceFromName(const QString &name)
QList< QSharedDataPointer< QNetworkInterfacePrivate > > allInterfaces()
QSharedDataPointer< QNetworkInterfacePrivate > interfaceFromIndex(int index)
QDebug operator<<(QDebug dbg, const QFileInfo &fi)
static QDebug flagsDebug(QDebug debug, QNetworkInterface::InterfaceFlags flags)