core/net/
ip_addr.rs

1use super::display_buffer::DisplayBuffer;
2use crate::cmp::Ordering;
3use crate::fmt::{self, Write};
4use crate::hash::{Hash, Hasher};
5use crate::iter;
6use crate::mem::transmute;
7use crate::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
8
9/// An IP address, either IPv4 or IPv6.
10///
11/// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
12/// respective documentation for more details.
13///
14/// # Examples
15///
16/// ```
17/// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
18///
19/// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
20/// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
21///
22/// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
23/// assert_eq!("::1".parse(), Ok(localhost_v6));
24///
25/// assert_eq!(localhost_v4.is_ipv6(), false);
26/// assert_eq!(localhost_v4.is_ipv4(), true);
27/// ```
28#[rustc_diagnostic_item = "IpAddr"]
29#[stable(feature = "ip_addr", since = "1.7.0")]
30#[derive(Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
31pub enum IpAddr {
32    /// An IPv4 address.
33    #[stable(feature = "ip_addr", since = "1.7.0")]
34    V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
35    /// An IPv6 address.
36    #[stable(feature = "ip_addr", since = "1.7.0")]
37    V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
38}
39
40/// An IPv4 address.
41///
42/// IPv4 addresses are defined as 32-bit integers in [IETF RFC 791].
43/// They are usually represented as four octets.
44///
45/// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
46///
47/// [IETF RFC 791]: https://tools.ietf.org/html/rfc791
48///
49/// # Textual representation
50///
51/// `Ipv4Addr` provides a [`FromStr`] implementation. The four octets are in decimal
52/// notation, divided by `.` (this is called "dot-decimal notation").
53/// Notably, octal numbers (which are indicated with a leading `0`) and hexadecimal numbers (which
54/// are indicated with a leading `0x`) are not allowed per [IETF RFC 6943].
55///
56/// [IETF RFC 6943]: https://tools.ietf.org/html/rfc6943#section-3.1.1
57/// [`FromStr`]: crate::str::FromStr
58///
59/// # Examples
60///
61/// ```
62/// use std::net::Ipv4Addr;
63///
64/// let localhost = Ipv4Addr::new(127, 0, 0, 1);
65/// assert_eq!("127.0.0.1".parse(), Ok(localhost));
66/// assert_eq!(localhost.is_loopback(), true);
67/// assert!("012.004.002.000".parse::<Ipv4Addr>().is_err()); // all octets are in octal
68/// assert!("0000000.0.0.0".parse::<Ipv4Addr>().is_err()); // first octet is a zero in octal
69/// assert!("0xcb.0x0.0x71.0x00".parse::<Ipv4Addr>().is_err()); // all octets are in hex
70/// ```
71#[rustc_diagnostic_item = "Ipv4Addr"]
72#[derive(Copy, Clone, PartialEq, Eq)]
73#[stable(feature = "rust1", since = "1.0.0")]
74pub struct Ipv4Addr {
75    octets: [u8; 4],
76}
77
78#[stable(feature = "rust1", since = "1.0.0")]
79impl Hash for Ipv4Addr {
80    fn hash<H: Hasher>(&self, state: &mut H) {
81        // Hashers are often more efficient at hashing a fixed-width integer
82        // than a bytestring, so convert before hashing. We don't use to_bits()
83        // here as that may involve a byteswap which is unnecessary.
84        u32::from_ne_bytes(self.octets).hash(state);
85    }
86}
87
88/// An IPv6 address.
89///
90/// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
91/// They are usually represented as eight 16-bit segments.
92///
93/// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
94///
95/// # Embedding IPv4 Addresses
96///
97/// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
98///
99/// To assist in the transition from IPv4 to IPv6 two types of IPv6 addresses that embed an IPv4 address were defined:
100/// IPv4-compatible and IPv4-mapped addresses. Of these IPv4-compatible addresses have been officially deprecated.
101///
102/// Both types of addresses are not assigned any special meaning by this implementation,
103/// other than what the relevant standards prescribe. This means that an address like `::ffff:127.0.0.1`,
104/// while representing an IPv4 loopback address, is not itself an IPv6 loopback address; only `::1` is.
105/// To handle these so called "IPv4-in-IPv6" addresses, they have to first be converted to their canonical IPv4 address.
106///
107/// ### IPv4-Compatible IPv6 Addresses
108///
109/// IPv4-compatible IPv6 addresses are defined in [IETF RFC 4291 Section 2.5.5.1], and have been officially deprecated.
110/// The RFC describes the format of an "IPv4-Compatible IPv6 address" as follows:
111///
112/// ```text
113/// |                80 bits               | 16 |      32 bits        |
114/// +--------------------------------------+--------------------------+
115/// |0000..............................0000|0000|    IPv4 address     |
116/// +--------------------------------------+----+---------------------+
117/// ```
118/// So `::a.b.c.d` would be an IPv4-compatible IPv6 address representing the IPv4 address `a.b.c.d`.
119///
120/// To convert from an IPv4 address to an IPv4-compatible IPv6 address, use [`Ipv4Addr::to_ipv6_compatible`].
121/// Use [`Ipv6Addr::to_ipv4`] to convert an IPv4-compatible IPv6 address to the canonical IPv4 address.
122///
123/// [IETF RFC 4291 Section 2.5.5.1]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.1
124///
125/// ### IPv4-Mapped IPv6 Addresses
126///
127/// IPv4-mapped IPv6 addresses are defined in [IETF RFC 4291 Section 2.5.5.2].
128/// The RFC describes the format of an "IPv4-Mapped IPv6 address" as follows:
129///
130/// ```text
131/// |                80 bits               | 16 |      32 bits        |
132/// +--------------------------------------+--------------------------+
133/// |0000..............................0000|FFFF|    IPv4 address     |
134/// +--------------------------------------+----+---------------------+
135/// ```
136/// So `::ffff:a.b.c.d` would be an IPv4-mapped IPv6 address representing the IPv4 address `a.b.c.d`.
137///
138/// To convert from an IPv4 address to an IPv4-mapped IPv6 address, use [`Ipv4Addr::to_ipv6_mapped`].
139/// Use [`Ipv6Addr::to_ipv4`] to convert an IPv4-mapped IPv6 address to the canonical IPv4 address.
140/// Note that this will also convert the IPv6 loopback address `::1` to `0.0.0.1`. Use
141/// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
142///
143/// [IETF RFC 4291 Section 2.5.5.2]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2
144///
145/// # Textual representation
146///
147/// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
148/// an IPv6 address in text, but in general, each segments is written in hexadecimal
149/// notation, and segments are separated by `:`. For more information, see
150/// [IETF RFC 5952].
151///
152/// [`FromStr`]: crate::str::FromStr
153/// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
154///
155/// # Examples
156///
157/// ```
158/// use std::net::Ipv6Addr;
159///
160/// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
161/// assert_eq!("::1".parse(), Ok(localhost));
162/// assert_eq!(localhost.is_loopback(), true);
163/// ```
164#[rustc_diagnostic_item = "Ipv6Addr"]
165#[derive(Copy, Clone, PartialEq, Eq)]
166#[stable(feature = "rust1", since = "1.0.0")]
167pub struct Ipv6Addr {
168    octets: [u8; 16],
169}
170
171#[stable(feature = "rust1", since = "1.0.0")]
172impl Hash for Ipv6Addr {
173    fn hash<H: Hasher>(&self, state: &mut H) {
174        // Hashers are often more efficient at hashing a fixed-width integer
175        // than a bytestring, so convert before hashing. We don't use to_bits()
176        // here as that may involve unnecessary byteswaps.
177        u128::from_ne_bytes(self.octets).hash(state);
178    }
179}
180
181/// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2].
182///
183/// # Stability Guarantees
184///
185/// Not all possible values for a multicast scope have been assigned.
186/// Future RFCs may introduce new scopes, which will be added as variants to this enum;
187/// because of this the enum is marked as `#[non_exhaustive]`.
188///
189/// # Examples
190/// ```
191/// #![feature(ip)]
192///
193/// use std::net::Ipv6Addr;
194/// use std::net::Ipv6MulticastScope::*;
195///
196/// // An IPv6 multicast address with global scope (`ff0e::`).
197/// let address = Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0);
198///
199/// // Will print "Global scope".
200/// match address.multicast_scope() {
201///     Some(InterfaceLocal) => println!("Interface-Local scope"),
202///     Some(LinkLocal) => println!("Link-Local scope"),
203///     Some(RealmLocal) => println!("Realm-Local scope"),
204///     Some(AdminLocal) => println!("Admin-Local scope"),
205///     Some(SiteLocal) => println!("Site-Local scope"),
206///     Some(OrganizationLocal) => println!("Organization-Local scope"),
207///     Some(Global) => println!("Global scope"),
208///     Some(_) => println!("Unknown scope"),
209///     None => println!("Not a multicast address!")
210/// }
211///
212/// ```
213///
214/// [IPv6 multicast address]: Ipv6Addr
215/// [IETF RFC 7346 section 2]: https://tools.ietf.org/html/rfc7346#section-2
216#[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
217#[unstable(feature = "ip", issue = "27709")]
218#[non_exhaustive]
219pub enum Ipv6MulticastScope {
220    /// Interface-Local scope.
221    InterfaceLocal,
222    /// Link-Local scope.
223    LinkLocal,
224    /// Realm-Local scope.
225    RealmLocal,
226    /// Admin-Local scope.
227    AdminLocal,
228    /// Site-Local scope.
229    SiteLocal,
230    /// Organization-Local scope.
231    OrganizationLocal,
232    /// Global scope.
233    Global,
234}
235
236impl IpAddr {
237    /// Returns [`true`] for the special 'unspecified' address.
238    ///
239    /// See the documentation for [`Ipv4Addr::is_unspecified()`] and
240    /// [`Ipv6Addr::is_unspecified()`] for more details.
241    ///
242    /// # Examples
243    ///
244    /// ```
245    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
246    ///
247    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
248    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
249    /// ```
250    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
251    #[stable(feature = "ip_shared", since = "1.12.0")]
252    #[must_use]
253    #[inline]
254    pub const fn is_unspecified(&self) -> bool {
255        match self {
256            IpAddr::V4(ip) => ip.is_unspecified(),
257            IpAddr::V6(ip) => ip.is_unspecified(),
258        }
259    }
260
261    /// Returns [`true`] if this is a loopback address.
262    ///
263    /// See the documentation for [`Ipv4Addr::is_loopback()`] and
264    /// [`Ipv6Addr::is_loopback()`] for more details.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
270    ///
271    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
272    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
273    /// ```
274    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
275    #[stable(feature = "ip_shared", since = "1.12.0")]
276    #[must_use]
277    #[inline]
278    pub const fn is_loopback(&self) -> bool {
279        match self {
280            IpAddr::V4(ip) => ip.is_loopback(),
281            IpAddr::V6(ip) => ip.is_loopback(),
282        }
283    }
284
285    /// Returns [`true`] if the address appears to be globally routable.
286    ///
287    /// See the documentation for [`Ipv4Addr::is_global()`] and
288    /// [`Ipv6Addr::is_global()`] for more details.
289    ///
290    /// # Examples
291    ///
292    /// ```
293    /// #![feature(ip)]
294    ///
295    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
296    ///
297    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
298    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
299    /// ```
300    #[unstable(feature = "ip", issue = "27709")]
301    #[must_use]
302    #[inline]
303    pub const fn is_global(&self) -> bool {
304        match self {
305            IpAddr::V4(ip) => ip.is_global(),
306            IpAddr::V6(ip) => ip.is_global(),
307        }
308    }
309
310    /// Returns [`true`] if this is a multicast address.
311    ///
312    /// See the documentation for [`Ipv4Addr::is_multicast()`] and
313    /// [`Ipv6Addr::is_multicast()`] for more details.
314    ///
315    /// # Examples
316    ///
317    /// ```
318    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
319    ///
320    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
321    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
322    /// ```
323    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
324    #[stable(feature = "ip_shared", since = "1.12.0")]
325    #[must_use]
326    #[inline]
327    pub const fn is_multicast(&self) -> bool {
328        match self {
329            IpAddr::V4(ip) => ip.is_multicast(),
330            IpAddr::V6(ip) => ip.is_multicast(),
331        }
332    }
333
334    /// Returns [`true`] if this address is in a range designated for documentation.
335    ///
336    /// See the documentation for [`Ipv4Addr::is_documentation()`] and
337    /// [`Ipv6Addr::is_documentation()`] for more details.
338    ///
339    /// # Examples
340    ///
341    /// ```
342    /// #![feature(ip)]
343    ///
344    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
345    ///
346    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
347    /// assert_eq!(
348    ///     IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
349    ///     true
350    /// );
351    /// ```
352    #[unstable(feature = "ip", issue = "27709")]
353    #[must_use]
354    #[inline]
355    pub const fn is_documentation(&self) -> bool {
356        match self {
357            IpAddr::V4(ip) => ip.is_documentation(),
358            IpAddr::V6(ip) => ip.is_documentation(),
359        }
360    }
361
362    /// Returns [`true`] if this address is in a range designated for benchmarking.
363    ///
364    /// See the documentation for [`Ipv4Addr::is_benchmarking()`] and
365    /// [`Ipv6Addr::is_benchmarking()`] for more details.
366    ///
367    /// # Examples
368    ///
369    /// ```
370    /// #![feature(ip)]
371    ///
372    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
373    ///
374    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(198, 19, 255, 255)).is_benchmarking(), true);
375    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0)).is_benchmarking(), true);
376    /// ```
377    #[unstable(feature = "ip", issue = "27709")]
378    #[must_use]
379    #[inline]
380    pub const fn is_benchmarking(&self) -> bool {
381        match self {
382            IpAddr::V4(ip) => ip.is_benchmarking(),
383            IpAddr::V6(ip) => ip.is_benchmarking(),
384        }
385    }
386
387    /// Returns [`true`] if this address is an [`IPv4` address], and [`false`]
388    /// otherwise.
389    ///
390    /// [`IPv4` address]: IpAddr::V4
391    ///
392    /// # Examples
393    ///
394    /// ```
395    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
396    ///
397    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
398    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
399    /// ```
400    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
401    #[stable(feature = "ipaddr_checker", since = "1.16.0")]
402    #[must_use]
403    #[inline]
404    pub const fn is_ipv4(&self) -> bool {
405        matches!(self, IpAddr::V4(_))
406    }
407
408    /// Returns [`true`] if this address is an [`IPv6` address], and [`false`]
409    /// otherwise.
410    ///
411    /// [`IPv6` address]: IpAddr::V6
412    ///
413    /// # Examples
414    ///
415    /// ```
416    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
417    ///
418    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
419    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
420    /// ```
421    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
422    #[stable(feature = "ipaddr_checker", since = "1.16.0")]
423    #[must_use]
424    #[inline]
425    pub const fn is_ipv6(&self) -> bool {
426        matches!(self, IpAddr::V6(_))
427    }
428
429    /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6
430    /// address, otherwise returns `self` as-is.
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
436    ///
437    /// let localhost_v4 = Ipv4Addr::new(127, 0, 0, 1);
438    ///
439    /// assert_eq!(IpAddr::V4(localhost_v4).to_canonical(), localhost_v4);
440    /// assert_eq!(IpAddr::V6(localhost_v4.to_ipv6_mapped()).to_canonical(), localhost_v4);
441    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).to_canonical().is_loopback(), true);
442    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).is_loopback(), false);
443    /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).to_canonical().is_loopback(), true);
444    /// ```
445    #[inline]
446    #[must_use = "this returns the result of the operation, \
447                  without modifying the original"]
448    #[stable(feature = "ip_to_canonical", since = "1.75.0")]
449    #[rustc_const_stable(feature = "ip_to_canonical", since = "1.75.0")]
450    pub const fn to_canonical(&self) -> IpAddr {
451        match self {
452            IpAddr::V4(_) => *self,
453            IpAddr::V6(v6) => v6.to_canonical(),
454        }
455    }
456
457    /// Returns the eight-bit integers this address consists of as a slice.
458    ///
459    /// # Examples
460    ///
461    /// ```
462    /// #![feature(ip_as_octets)]
463    ///
464    /// use std::net::{Ipv4Addr, Ipv6Addr, IpAddr};
465    ///
466    /// assert_eq!(IpAddr::V4(Ipv4Addr::LOCALHOST).as_octets(), &[127, 0, 0, 1]);
467    /// assert_eq!(IpAddr::V6(Ipv6Addr::LOCALHOST).as_octets(),
468    ///            &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
469    /// ```
470    #[unstable(feature = "ip_as_octets", issue = "137259")]
471    #[inline]
472    pub const fn as_octets(&self) -> &[u8] {
473        match self {
474            IpAddr::V4(ip) => ip.as_octets().as_slice(),
475            IpAddr::V6(ip) => ip.as_octets().as_slice(),
476        }
477    }
478}
479
480impl Ipv4Addr {
481    /// Creates a new IPv4 address from four eight-bit octets.
482    ///
483    /// The result will represent the IP address `a`.`b`.`c`.`d`.
484    ///
485    /// # Examples
486    ///
487    /// ```
488    /// use std::net::Ipv4Addr;
489    ///
490    /// let addr = Ipv4Addr::new(127, 0, 0, 1);
491    /// ```
492    #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
493    #[stable(feature = "rust1", since = "1.0.0")]
494    #[must_use]
495    #[inline]
496    pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
497        Ipv4Addr { octets: [a, b, c, d] }
498    }
499
500    /// The size of an IPv4 address in bits.
501    ///
502    /// # Examples
503    ///
504    /// ```
505    /// use std::net::Ipv4Addr;
506    ///
507    /// assert_eq!(Ipv4Addr::BITS, 32);
508    /// ```
509    #[stable(feature = "ip_bits", since = "1.80.0")]
510    pub const BITS: u32 = 32;
511
512    /// Converts an IPv4 address into a `u32` representation using native byte order.
513    ///
514    /// Although IPv4 addresses are big-endian, the `u32` value will use the target platform's
515    /// native byte order. That is, the `u32` value is an integer representation of the IPv4
516    /// address and not an integer interpretation of the IPv4 address's big-endian bitstring. This
517    /// means that the `u32` value masked with `0xffffff00` will set the last octet in the address
518    /// to 0, regardless of the target platform's endianness.
519    ///
520    /// # Examples
521    ///
522    /// ```
523    /// use std::net::Ipv4Addr;
524    ///
525    /// let addr = Ipv4Addr::new(0x12, 0x34, 0x56, 0x78);
526    /// assert_eq!(0x12345678, addr.to_bits());
527    /// ```
528    ///
529    /// ```
530    /// use std::net::Ipv4Addr;
531    ///
532    /// let addr = Ipv4Addr::new(0x12, 0x34, 0x56, 0x78);
533    /// let addr_bits = addr.to_bits() & 0xffffff00;
534    /// assert_eq!(Ipv4Addr::new(0x12, 0x34, 0x56, 0x00), Ipv4Addr::from_bits(addr_bits));
535    ///
536    /// ```
537    #[rustc_const_stable(feature = "ip_bits", since = "1.80.0")]
538    #[stable(feature = "ip_bits", since = "1.80.0")]
539    #[must_use]
540    #[inline]
541    pub const fn to_bits(self) -> u32 {
542        u32::from_be_bytes(self.octets)
543    }
544
545    /// Converts a native byte order `u32` into an IPv4 address.
546    ///
547    /// See [`Ipv4Addr::to_bits`] for an explanation on endianness.
548    ///
549    /// # Examples
550    ///
551    /// ```
552    /// use std::net::Ipv4Addr;
553    ///
554    /// let addr = Ipv4Addr::from_bits(0x12345678);
555    /// assert_eq!(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78), addr);
556    /// ```
557    #[rustc_const_stable(feature = "ip_bits", since = "1.80.0")]
558    #[stable(feature = "ip_bits", since = "1.80.0")]
559    #[must_use]
560    #[inline]
561    pub const fn from_bits(bits: u32) -> Ipv4Addr {
562        Ipv4Addr { octets: bits.to_be_bytes() }
563    }
564
565    /// An IPv4 address with the address pointing to localhost: `127.0.0.1`
566    ///
567    /// # Examples
568    ///
569    /// ```
570    /// use std::net::Ipv4Addr;
571    ///
572    /// let addr = Ipv4Addr::LOCALHOST;
573    /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
574    /// ```
575    #[stable(feature = "ip_constructors", since = "1.30.0")]
576    pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
577
578    /// An IPv4 address representing an unspecified address: `0.0.0.0`
579    ///
580    /// This corresponds to the constant `INADDR_ANY` in other languages.
581    ///
582    /// # Examples
583    ///
584    /// ```
585    /// use std::net::Ipv4Addr;
586    ///
587    /// let addr = Ipv4Addr::UNSPECIFIED;
588    /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
589    /// ```
590    #[doc(alias = "INADDR_ANY")]
591    #[stable(feature = "ip_constructors", since = "1.30.0")]
592    pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
593
594    /// An IPv4 address representing the broadcast address: `255.255.255.255`.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// use std::net::Ipv4Addr;
600    ///
601    /// let addr = Ipv4Addr::BROADCAST;
602    /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
603    /// ```
604    #[stable(feature = "ip_constructors", since = "1.30.0")]
605    pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
606
607    /// Returns the four eight-bit integers that make up this address.
608    ///
609    /// # Examples
610    ///
611    /// ```
612    /// use std::net::Ipv4Addr;
613    ///
614    /// let addr = Ipv4Addr::new(127, 0, 0, 1);
615    /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
616    /// ```
617    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
618    #[stable(feature = "rust1", since = "1.0.0")]
619    #[must_use]
620    #[inline]
621    pub const fn octets(&self) -> [u8; 4] {
622        self.octets
623    }
624
625    /// Creates an `Ipv4Addr` from a four element byte array.
626    ///
627    /// # Examples
628    ///
629    /// ```
630    /// #![feature(ip_from)]
631    /// use std::net::Ipv4Addr;
632    ///
633    /// let addr = Ipv4Addr::from_octets([13u8, 12u8, 11u8, 10u8]);
634    /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
635    /// ```
636    #[unstable(feature = "ip_from", issue = "131360")]
637    #[must_use]
638    #[inline]
639    pub const fn from_octets(octets: [u8; 4]) -> Ipv4Addr {
640        Ipv4Addr { octets }
641    }
642
643    /// Returns the four eight-bit integers that make up this address
644    /// as a slice.
645    ///
646    /// # Examples
647    ///
648    /// ```
649    /// #![feature(ip_as_octets)]
650    ///
651    /// use std::net::Ipv4Addr;
652    ///
653    /// let addr = Ipv4Addr::new(127, 0, 0, 1);
654    /// assert_eq!(addr.as_octets(), &[127, 0, 0, 1]);
655    /// ```
656    #[unstable(feature = "ip_as_octets", issue = "137259")]
657    #[inline]
658    pub const fn as_octets(&self) -> &[u8; 4] {
659        &self.octets
660    }
661
662    /// Returns [`true`] for the special 'unspecified' address (`0.0.0.0`).
663    ///
664    /// This property is defined in _UNIX Network Programming, Second Edition_,
665    /// W. Richard Stevens, p. 891; see also [ip7].
666    ///
667    /// [ip7]: https://man7.org/linux/man-pages/man7/ip.7.html
668    ///
669    /// # Examples
670    ///
671    /// ```
672    /// use std::net::Ipv4Addr;
673    ///
674    /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
675    /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
676    /// ```
677    #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
678    #[stable(feature = "ip_shared", since = "1.12.0")]
679    #[must_use]
680    #[inline]
681    pub const fn is_unspecified(&self) -> bool {
682        u32::from_be_bytes(self.octets) == 0
683    }
684
685    /// Returns [`true`] if this is a loopback address (`127.0.0.0/8`).
686    ///
687    /// This property is defined by [IETF RFC 1122].
688    ///
689    /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
690    ///
691    /// # Examples
692    ///
693    /// ```
694    /// use std::net::Ipv4Addr;
695    ///
696    /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
697    /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
698    /// ```
699    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
700    #[stable(since = "1.7.0", feature = "ip_17")]
701    #[must_use]
702    #[inline]
703    pub const fn is_loopback(&self) -> bool {
704        self.octets()[0] == 127
705    }
706
707    /// Returns [`true`] if this is a private address.
708    ///
709    /// The private address ranges are defined in [IETF RFC 1918] and include:
710    ///
711    ///  - `10.0.0.0/8`
712    ///  - `172.16.0.0/12`
713    ///  - `192.168.0.0/16`
714    ///
715    /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
716    ///
717    /// # Examples
718    ///
719    /// ```
720    /// use std::net::Ipv4Addr;
721    ///
722    /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
723    /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
724    /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
725    /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
726    /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
727    /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
728    /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
729    /// ```
730    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
731    #[stable(since = "1.7.0", feature = "ip_17")]
732    #[must_use]
733    #[inline]
734    pub const fn is_private(&self) -> bool {
735        match self.octets() {
736            [10, ..] => true,
737            [172, b, ..] if b >= 16 && b <= 31 => true,
738            [192, 168, ..] => true,
739            _ => false,
740        }
741    }
742
743    /// Returns [`true`] if the address is link-local (`169.254.0.0/16`).
744    ///
745    /// This property is defined by [IETF RFC 3927].
746    ///
747    /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
748    ///
749    /// # Examples
750    ///
751    /// ```
752    /// use std::net::Ipv4Addr;
753    ///
754    /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
755    /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
756    /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
757    /// ```
758    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
759    #[stable(since = "1.7.0", feature = "ip_17")]
760    #[must_use]
761    #[inline]
762    pub const fn is_link_local(&self) -> bool {
763        matches!(self.octets(), [169, 254, ..])
764    }
765
766    /// Returns [`true`] if the address appears to be globally reachable
767    /// as specified by the [IANA IPv4 Special-Purpose Address Registry].
768    ///
769    /// Whether or not an address is practically reachable will depend on your
770    /// network configuration. Most IPv4 addresses are globally reachable, unless
771    /// they are specifically defined as *not* globally reachable.
772    ///
773    /// Non-exhaustive list of notable addresses that are not globally reachable:
774    ///
775    /// - The [unspecified address] ([`is_unspecified`](Ipv4Addr::is_unspecified))
776    /// - Addresses reserved for private use ([`is_private`](Ipv4Addr::is_private))
777    /// - Addresses in the shared address space ([`is_shared`](Ipv4Addr::is_shared))
778    /// - Loopback addresses ([`is_loopback`](Ipv4Addr::is_loopback))
779    /// - Link-local addresses ([`is_link_local`](Ipv4Addr::is_link_local))
780    /// - Addresses reserved for documentation ([`is_documentation`](Ipv4Addr::is_documentation))
781    /// - Addresses reserved for benchmarking ([`is_benchmarking`](Ipv4Addr::is_benchmarking))
782    /// - Reserved addresses ([`is_reserved`](Ipv4Addr::is_reserved))
783    /// - The [broadcast address] ([`is_broadcast`](Ipv4Addr::is_broadcast))
784    ///
785    /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv4 Special-Purpose Address Registry].
786    ///
787    /// [IANA IPv4 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
788    /// [unspecified address]: Ipv4Addr::UNSPECIFIED
789    /// [broadcast address]: Ipv4Addr::BROADCAST
790
791    ///
792    /// # Examples
793    ///
794    /// ```
795    /// #![feature(ip)]
796    ///
797    /// use std::net::Ipv4Addr;
798    ///
799    /// // Most IPv4 addresses are globally reachable:
800    /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
801    ///
802    /// // However some addresses have been assigned a special meaning
803    /// // that makes them not globally reachable. Some examples are:
804    ///
805    /// // The unspecified address (`0.0.0.0`)
806    /// assert_eq!(Ipv4Addr::UNSPECIFIED.is_global(), false);
807    ///
808    /// // Addresses reserved for private use (`10.0.0.0/8`, `172.16.0.0/12`, 192.168.0.0/16)
809    /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
810    /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
811    /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
812    ///
813    /// // Addresses in the shared address space (`100.64.0.0/10`)
814    /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
815    ///
816    /// // The loopback addresses (`127.0.0.0/8`)
817    /// assert_eq!(Ipv4Addr::LOCALHOST.is_global(), false);
818    ///
819    /// // Link-local addresses (`169.254.0.0/16`)
820    /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
821    ///
822    /// // Addresses reserved for documentation (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`)
823    /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
824    /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
825    /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
826    ///
827    /// // Addresses reserved for benchmarking (`198.18.0.0/15`)
828    /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
829    ///
830    /// // Reserved addresses (`240.0.0.0/4`)
831    /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
832    ///
833    /// // The broadcast address (`255.255.255.255`)
834    /// assert_eq!(Ipv4Addr::BROADCAST.is_global(), false);
835    ///
836    /// // For a complete overview see the IANA IPv4 Special-Purpose Address Registry.
837    /// ```
838    #[unstable(feature = "ip", issue = "27709")]
839    #[must_use]
840    #[inline]
841    pub const fn is_global(&self) -> bool {
842        !(self.octets()[0] == 0 // "This network"
843            || self.is_private()
844            || self.is_shared()
845            || self.is_loopback()
846            || self.is_link_local()
847            // addresses reserved for future protocols (`192.0.0.0/24`)
848            // .9 and .10 are documented as globally reachable so they're excluded
849            || (
850                self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0
851                && self.octets()[3] != 9 && self.octets()[3] != 10
852            )
853            || self.is_documentation()
854            || self.is_benchmarking()
855            || self.is_reserved()
856            || self.is_broadcast())
857    }
858
859    /// Returns [`true`] if this address is part of the Shared Address Space defined in
860    /// [IETF RFC 6598] (`100.64.0.0/10`).
861    ///
862    /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
863    ///
864    /// # Examples
865    ///
866    /// ```
867    /// #![feature(ip)]
868    /// use std::net::Ipv4Addr;
869    ///
870    /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
871    /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
872    /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
873    /// ```
874    #[unstable(feature = "ip", issue = "27709")]
875    #[must_use]
876    #[inline]
877    pub const fn is_shared(&self) -> bool {
878        self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
879    }
880
881    /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
882    /// network devices benchmarking.
883    ///
884    /// This range is defined in [IETF RFC 2544] as `192.18.0.0` through
885    /// `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
886    ///
887    /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
888    /// [errata 423]: https://www.rfc-editor.org/errata/eid423
889    ///
890    /// # Examples
891    ///
892    /// ```
893    /// #![feature(ip)]
894    /// use std::net::Ipv4Addr;
895    ///
896    /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
897    /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
898    /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
899    /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
900    /// ```
901    #[unstable(feature = "ip", issue = "27709")]
902    #[must_use]
903    #[inline]
904    pub const fn is_benchmarking(&self) -> bool {
905        self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
906    }
907
908    /// Returns [`true`] if this address is reserved by IANA for future use.
909    ///
910    /// [IETF RFC 1112] defines the block of reserved addresses as `240.0.0.0/4`.
911    /// This range normally includes the broadcast address `255.255.255.255`, but
912    /// this implementation explicitly excludes it, since it is obviously not
913    /// reserved for future use.
914    ///
915    /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
916    ///
917    /// # Warning
918    ///
919    /// As IANA assigns new addresses, this method will be
920    /// updated. This may result in non-reserved addresses being
921    /// treated as reserved in code that relies on an outdated version
922    /// of this method.
923    ///
924    /// # Examples
925    ///
926    /// ```
927    /// #![feature(ip)]
928    /// use std::net::Ipv4Addr;
929    ///
930    /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
931    /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
932    ///
933    /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
934    /// // The broadcast address is not considered as reserved for future use by this implementation
935    /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
936    /// ```
937    #[unstable(feature = "ip", issue = "27709")]
938    #[must_use]
939    #[inline]
940    pub const fn is_reserved(&self) -> bool {
941        self.octets()[0] & 240 == 240 && !self.is_broadcast()
942    }
943
944    /// Returns [`true`] if this is a multicast address (`224.0.0.0/4`).
945    ///
946    /// Multicast addresses have a most significant octet between `224` and `239`,
947    /// and is defined by [IETF RFC 5771].
948    ///
949    /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
950    ///
951    /// # Examples
952    ///
953    /// ```
954    /// use std::net::Ipv4Addr;
955    ///
956    /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
957    /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
958    /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
959    /// ```
960    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
961    #[stable(since = "1.7.0", feature = "ip_17")]
962    #[must_use]
963    #[inline]
964    pub const fn is_multicast(&self) -> bool {
965        self.octets()[0] >= 224 && self.octets()[0] <= 239
966    }
967
968    /// Returns [`true`] if this is a broadcast address (`255.255.255.255`).
969    ///
970    /// A broadcast address has all octets set to `255` as defined in [IETF RFC 919].
971    ///
972    /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
973    ///
974    /// # Examples
975    ///
976    /// ```
977    /// use std::net::Ipv4Addr;
978    ///
979    /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
980    /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
981    /// ```
982    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
983    #[stable(since = "1.7.0", feature = "ip_17")]
984    #[must_use]
985    #[inline]
986    pub const fn is_broadcast(&self) -> bool {
987        u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
988    }
989
990    /// Returns [`true`] if this address is in a range designated for documentation.
991    ///
992    /// This is defined in [IETF RFC 5737]:
993    ///
994    /// - `192.0.2.0/24` (TEST-NET-1)
995    /// - `198.51.100.0/24` (TEST-NET-2)
996    /// - `203.0.113.0/24` (TEST-NET-3)
997    ///
998    /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
999    ///
1000    /// # Examples
1001    ///
1002    /// ```
1003    /// use std::net::Ipv4Addr;
1004    ///
1005    /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
1006    /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
1007    /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
1008    /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
1009    /// ```
1010    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1011    #[stable(since = "1.7.0", feature = "ip_17")]
1012    #[must_use]
1013    #[inline]
1014    pub const fn is_documentation(&self) -> bool {
1015        matches!(self.octets(), [192, 0, 2, _] | [198, 51, 100, _] | [203, 0, 113, _])
1016    }
1017
1018    /// Converts this address to an [IPv4-compatible] [`IPv6` address].
1019    ///
1020    /// `a.b.c.d` becomes `::a.b.c.d`
1021    ///
1022    /// Note that IPv4-compatible addresses have been officially deprecated.
1023    /// If you don't explicitly need an IPv4-compatible address for legacy reasons, consider using `to_ipv6_mapped` instead.
1024    ///
1025    /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
1026    /// [`IPv6` address]: Ipv6Addr
1027    ///
1028    /// # Examples
1029    ///
1030    /// ```
1031    /// use std::net::{Ipv4Addr, Ipv6Addr};
1032    ///
1033    /// assert_eq!(
1034    ///     Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
1035    ///     Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x2ff)
1036    /// );
1037    /// ```
1038    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1039    #[stable(feature = "rust1", since = "1.0.0")]
1040    #[must_use = "this returns the result of the operation, \
1041                  without modifying the original"]
1042    #[inline]
1043    pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
1044        let [a, b, c, d] = self.octets();
1045        Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] }
1046    }
1047
1048    /// Converts this address to an [IPv4-mapped] [`IPv6` address].
1049    ///
1050    /// `a.b.c.d` becomes `::ffff:a.b.c.d`
1051    ///
1052    /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
1053    /// [`IPv6` address]: Ipv6Addr
1054    ///
1055    /// # Examples
1056    ///
1057    /// ```
1058    /// use std::net::{Ipv4Addr, Ipv6Addr};
1059    ///
1060    /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
1061    ///            Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff));
1062    /// ```
1063    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1064    #[stable(feature = "rust1", since = "1.0.0")]
1065    #[must_use = "this returns the result of the operation, \
1066                  without modifying the original"]
1067    #[inline]
1068    pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
1069        let [a, b, c, d] = self.octets();
1070        Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] }
1071    }
1072}
1073
1074#[stable(feature = "ip_addr", since = "1.7.0")]
1075impl fmt::Display for IpAddr {
1076    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1077        match self {
1078            IpAddr::V4(ip) => ip.fmt(fmt),
1079            IpAddr::V6(ip) => ip.fmt(fmt),
1080        }
1081    }
1082}
1083
1084#[stable(feature = "ip_addr", since = "1.7.0")]
1085impl fmt::Debug for IpAddr {
1086    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1087        fmt::Display::fmt(self, fmt)
1088    }
1089}
1090
1091#[stable(feature = "ip_from_ip", since = "1.16.0")]
1092impl From<Ipv4Addr> for IpAddr {
1093    /// Copies this address to a new `IpAddr::V4`.
1094    ///
1095    /// # Examples
1096    ///
1097    /// ```
1098    /// use std::net::{IpAddr, Ipv4Addr};
1099    ///
1100    /// let addr = Ipv4Addr::new(127, 0, 0, 1);
1101    ///
1102    /// assert_eq!(
1103    ///     IpAddr::V4(addr),
1104    ///     IpAddr::from(addr)
1105    /// )
1106    /// ```
1107    #[inline]
1108    fn from(ipv4: Ipv4Addr) -> IpAddr {
1109        IpAddr::V4(ipv4)
1110    }
1111}
1112
1113#[stable(feature = "ip_from_ip", since = "1.16.0")]
1114impl From<Ipv6Addr> for IpAddr {
1115    /// Copies this address to a new `IpAddr::V6`.
1116    ///
1117    /// # Examples
1118    ///
1119    /// ```
1120    /// use std::net::{IpAddr, Ipv6Addr};
1121    ///
1122    /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1123    ///
1124    /// assert_eq!(
1125    ///     IpAddr::V6(addr),
1126    ///     IpAddr::from(addr)
1127    /// );
1128    /// ```
1129    #[inline]
1130    fn from(ipv6: Ipv6Addr) -> IpAddr {
1131        IpAddr::V6(ipv6)
1132    }
1133}
1134
1135#[stable(feature = "rust1", since = "1.0.0")]
1136impl fmt::Display for Ipv4Addr {
1137    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1138        let octets = self.octets();
1139
1140        // If there are no alignment requirements, write the IP address directly to `f`.
1141        // Otherwise, write it to a local buffer and then use `f.pad`.
1142        if fmt.precision().is_none() && fmt.width().is_none() {
1143            write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
1144        } else {
1145            const LONGEST_IPV4_ADDR: &str = "255.255.255.255";
1146
1147            let mut buf = DisplayBuffer::<{ LONGEST_IPV4_ADDR.len() }>::new();
1148            // Buffer is long enough for the longest possible IPv4 address, so this should never fail.
1149            write!(buf, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
1150
1151            fmt.pad(buf.as_str())
1152        }
1153    }
1154}
1155
1156#[stable(feature = "rust1", since = "1.0.0")]
1157impl fmt::Debug for Ipv4Addr {
1158    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1159        fmt::Display::fmt(self, fmt)
1160    }
1161}
1162
1163#[stable(feature = "ip_cmp", since = "1.16.0")]
1164impl PartialEq<Ipv4Addr> for IpAddr {
1165    #[inline]
1166    fn eq(&self, other: &Ipv4Addr) -> bool {
1167        match self {
1168            IpAddr::V4(v4) => v4 == other,
1169            IpAddr::V6(_) => false,
1170        }
1171    }
1172}
1173
1174#[stable(feature = "ip_cmp", since = "1.16.0")]
1175impl PartialEq<IpAddr> for Ipv4Addr {
1176    #[inline]
1177    fn eq(&self, other: &IpAddr) -> bool {
1178        match other {
1179            IpAddr::V4(v4) => self == v4,
1180            IpAddr::V6(_) => false,
1181        }
1182    }
1183}
1184
1185#[stable(feature = "rust1", since = "1.0.0")]
1186impl PartialOrd for Ipv4Addr {
1187    #[inline]
1188    fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1189        Some(self.cmp(other))
1190    }
1191}
1192
1193#[stable(feature = "ip_cmp", since = "1.16.0")]
1194impl PartialOrd<Ipv4Addr> for IpAddr {
1195    #[inline]
1196    fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1197        match self {
1198            IpAddr::V4(v4) => v4.partial_cmp(other),
1199            IpAddr::V6(_) => Some(Ordering::Greater),
1200        }
1201    }
1202}
1203
1204#[stable(feature = "ip_cmp", since = "1.16.0")]
1205impl PartialOrd<IpAddr> for Ipv4Addr {
1206    #[inline]
1207    fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1208        match other {
1209            IpAddr::V4(v4) => self.partial_cmp(v4),
1210            IpAddr::V6(_) => Some(Ordering::Less),
1211        }
1212    }
1213}
1214
1215#[stable(feature = "rust1", since = "1.0.0")]
1216impl Ord for Ipv4Addr {
1217    #[inline]
1218    fn cmp(&self, other: &Ipv4Addr) -> Ordering {
1219        self.octets.cmp(&other.octets)
1220    }
1221}
1222
1223#[stable(feature = "ip_u32", since = "1.1.0")]
1224impl From<Ipv4Addr> for u32 {
1225    /// Uses [`Ipv4Addr::to_bits`] to convert an IPv4 address to a host byte order `u32`.
1226    #[inline]
1227    fn from(ip: Ipv4Addr) -> u32 {
1228        ip.to_bits()
1229    }
1230}
1231
1232#[stable(feature = "ip_u32", since = "1.1.0")]
1233impl From<u32> for Ipv4Addr {
1234    /// Uses [`Ipv4Addr::from_bits`] to convert a host byte order `u32` into an IPv4 address.
1235    #[inline]
1236    fn from(ip: u32) -> Ipv4Addr {
1237        Ipv4Addr::from_bits(ip)
1238    }
1239}
1240
1241#[stable(feature = "from_slice_v4", since = "1.9.0")]
1242impl From<[u8; 4]> for Ipv4Addr {
1243    /// Creates an `Ipv4Addr` from a four element byte array.
1244    ///
1245    /// # Examples
1246    ///
1247    /// ```
1248    /// use std::net::Ipv4Addr;
1249    ///
1250    /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1251    /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1252    /// ```
1253    #[inline]
1254    fn from(octets: [u8; 4]) -> Ipv4Addr {
1255        Ipv4Addr { octets }
1256    }
1257}
1258
1259#[stable(feature = "ip_from_slice", since = "1.17.0")]
1260impl From<[u8; 4]> for IpAddr {
1261    /// Creates an `IpAddr::V4` from a four element byte array.
1262    ///
1263    /// # Examples
1264    ///
1265    /// ```
1266    /// use std::net::{IpAddr, Ipv4Addr};
1267    ///
1268    /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1269    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1270    /// ```
1271    #[inline]
1272    fn from(octets: [u8; 4]) -> IpAddr {
1273        IpAddr::V4(Ipv4Addr::from(octets))
1274    }
1275}
1276
1277impl Ipv6Addr {
1278    /// Creates a new IPv6 address from eight 16-bit segments.
1279    ///
1280    /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1281    ///
1282    /// # Examples
1283    ///
1284    /// ```
1285    /// use std::net::Ipv6Addr;
1286    ///
1287    /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1288    /// ```
1289    #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
1290    #[stable(feature = "rust1", since = "1.0.0")]
1291    #[must_use]
1292    #[inline]
1293    pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1294        let addr16 = [
1295            a.to_be(),
1296            b.to_be(),
1297            c.to_be(),
1298            d.to_be(),
1299            e.to_be(),
1300            f.to_be(),
1301            g.to_be(),
1302            h.to_be(),
1303        ];
1304        Ipv6Addr {
1305            // All elements in `addr16` are big endian.
1306            // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1307            octets: unsafe { transmute::<_, [u8; 16]>(addr16) },
1308        }
1309    }
1310
1311    /// The size of an IPv6 address in bits.
1312    ///
1313    /// # Examples
1314    ///
1315    /// ```
1316    /// use std::net::Ipv6Addr;
1317    ///
1318    /// assert_eq!(Ipv6Addr::BITS, 128);
1319    /// ```
1320    #[stable(feature = "ip_bits", since = "1.80.0")]
1321    pub const BITS: u32 = 128;
1322
1323    /// Converts an IPv6 address into a `u128` representation using native byte order.
1324    ///
1325    /// Although IPv6 addresses are big-endian, the `u128` value will use the target platform's
1326    /// native byte order. That is, the `u128` value is an integer representation of the IPv6
1327    /// address and not an integer interpretation of the IPv6 address's big-endian bitstring. This
1328    /// means that the `u128` value masked with `0xffffffffffffffffffffffffffff0000_u128` will set
1329    /// the last segment in the address to 0, regardless of the target platform's endianness.
1330    ///
1331    /// # Examples
1332    ///
1333    /// ```
1334    /// use std::net::Ipv6Addr;
1335    ///
1336    /// let addr = Ipv6Addr::new(
1337    ///     0x1020, 0x3040, 0x5060, 0x7080,
1338    ///     0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1339    /// );
1340    /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, addr.to_bits());
1341    /// ```
1342    ///
1343    /// ```
1344    /// use std::net::Ipv6Addr;
1345    ///
1346    /// let addr = Ipv6Addr::new(
1347    ///     0x1020, 0x3040, 0x5060, 0x7080,
1348    ///     0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1349    /// );
1350    /// let addr_bits = addr.to_bits() & 0xffffffffffffffffffffffffffff0000_u128;
1351    /// assert_eq!(
1352    ///     Ipv6Addr::new(
1353    ///         0x1020, 0x3040, 0x5060, 0x7080,
1354    ///         0x90A0, 0xB0C0, 0xD0E0, 0x0000,
1355    ///     ),
1356    ///     Ipv6Addr::from_bits(addr_bits));
1357    ///
1358    /// ```
1359    #[rustc_const_stable(feature = "ip_bits", since = "1.80.0")]
1360    #[stable(feature = "ip_bits", since = "1.80.0")]
1361    #[must_use]
1362    #[inline]
1363    pub const fn to_bits(self) -> u128 {
1364        u128::from_be_bytes(self.octets)
1365    }
1366
1367    /// Converts a native byte order `u128` into an IPv6 address.
1368    ///
1369    /// See [`Ipv6Addr::to_bits`] for an explanation on endianness.
1370    ///
1371    /// # Examples
1372    ///
1373    /// ```
1374    /// use std::net::Ipv6Addr;
1375    ///
1376    /// let addr = Ipv6Addr::from_bits(0x102030405060708090A0B0C0D0E0F00D_u128);
1377    /// assert_eq!(
1378    ///     Ipv6Addr::new(
1379    ///         0x1020, 0x3040, 0x5060, 0x7080,
1380    ///         0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1381    ///     ),
1382    ///     addr);
1383    /// ```
1384    #[rustc_const_stable(feature = "ip_bits", since = "1.80.0")]
1385    #[stable(feature = "ip_bits", since = "1.80.0")]
1386    #[must_use]
1387    #[inline]
1388    pub const fn from_bits(bits: u128) -> Ipv6Addr {
1389        Ipv6Addr { octets: bits.to_be_bytes() }
1390    }
1391
1392    /// An IPv6 address representing localhost: `::1`.
1393    ///
1394    /// This corresponds to constant `IN6ADDR_LOOPBACK_INIT` or `in6addr_loopback` in other
1395    /// languages.
1396    ///
1397    /// # Examples
1398    ///
1399    /// ```
1400    /// use std::net::Ipv6Addr;
1401    ///
1402    /// let addr = Ipv6Addr::LOCALHOST;
1403    /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1404    /// ```
1405    #[doc(alias = "IN6ADDR_LOOPBACK_INIT")]
1406    #[doc(alias = "in6addr_loopback")]
1407    #[stable(feature = "ip_constructors", since = "1.30.0")]
1408    pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1409
1410    /// An IPv6 address representing the unspecified address: `::`.
1411    ///
1412    /// This corresponds to constant `IN6ADDR_ANY_INIT` or `in6addr_any` in other languages.
1413    ///
1414    /// # Examples
1415    ///
1416    /// ```
1417    /// use std::net::Ipv6Addr;
1418    ///
1419    /// let addr = Ipv6Addr::UNSPECIFIED;
1420    /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1421    /// ```
1422    #[doc(alias = "IN6ADDR_ANY_INIT")]
1423    #[doc(alias = "in6addr_any")]
1424    #[stable(feature = "ip_constructors", since = "1.30.0")]
1425    pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1426
1427    /// Returns the eight 16-bit segments that make up this address.
1428    ///
1429    /// # Examples
1430    ///
1431    /// ```
1432    /// use std::net::Ipv6Addr;
1433    ///
1434    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1435    ///            [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1436    /// ```
1437    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1438    #[stable(feature = "rust1", since = "1.0.0")]
1439    #[must_use]
1440    #[inline]
1441    pub const fn segments(&self) -> [u16; 8] {
1442        // All elements in `self.octets` must be big endian.
1443        // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1444        let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.octets) };
1445        // We want native endian u16
1446        [
1447            u16::from_be(a),
1448            u16::from_be(b),
1449            u16::from_be(c),
1450            u16::from_be(d),
1451            u16::from_be(e),
1452            u16::from_be(f),
1453            u16::from_be(g),
1454            u16::from_be(h),
1455        ]
1456    }
1457
1458    /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1459    ///
1460    /// # Examples
1461    ///
1462    /// ```
1463    /// #![feature(ip_from)]
1464    /// use std::net::Ipv6Addr;
1465    ///
1466    /// let addr = Ipv6Addr::from_segments([
1467    ///     0x20du16, 0x20cu16, 0x20bu16, 0x20au16,
1468    ///     0x209u16, 0x208u16, 0x207u16, 0x206u16,
1469    /// ]);
1470    /// assert_eq!(
1471    ///     Ipv6Addr::new(
1472    ///         0x20d, 0x20c, 0x20b, 0x20a,
1473    ///         0x209, 0x208, 0x207, 0x206,
1474    ///     ),
1475    ///     addr
1476    /// );
1477    /// ```
1478    #[unstable(feature = "ip_from", issue = "131360")]
1479    #[must_use]
1480    #[inline]
1481    pub const fn from_segments(segments: [u16; 8]) -> Ipv6Addr {
1482        let [a, b, c, d, e, f, g, h] = segments;
1483        Ipv6Addr::new(a, b, c, d, e, f, g, h)
1484    }
1485
1486    /// Returns [`true`] for the special 'unspecified' address (`::`).
1487    ///
1488    /// This property is defined in [IETF RFC 4291].
1489    ///
1490    /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1491    ///
1492    /// # Examples
1493    ///
1494    /// ```
1495    /// use std::net::Ipv6Addr;
1496    ///
1497    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1498    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1499    /// ```
1500    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1501    #[stable(since = "1.7.0", feature = "ip_17")]
1502    #[must_use]
1503    #[inline]
1504    pub const fn is_unspecified(&self) -> bool {
1505        u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1506    }
1507
1508    /// Returns [`true`] if this is the [loopback address] (`::1`),
1509    /// as defined in [IETF RFC 4291 section 2.5.3].
1510    ///
1511    /// Contrary to IPv4, in IPv6 there is only one loopback address.
1512    ///
1513    /// [loopback address]: Ipv6Addr::LOCALHOST
1514    /// [IETF RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1515    ///
1516    /// # Examples
1517    ///
1518    /// ```
1519    /// use std::net::Ipv6Addr;
1520    ///
1521    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1522    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1523    /// ```
1524    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1525    #[stable(since = "1.7.0", feature = "ip_17")]
1526    #[must_use]
1527    #[inline]
1528    pub const fn is_loopback(&self) -> bool {
1529        u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1530    }
1531
1532    /// Returns [`true`] if the address appears to be globally reachable
1533    /// as specified by the [IANA IPv6 Special-Purpose Address Registry].
1534    ///
1535    /// Whether or not an address is practically reachable will depend on your
1536    /// network configuration. Most IPv6 addresses are globally reachable, unless
1537    /// they are specifically defined as *not* globally reachable.
1538    ///
1539    /// Non-exhaustive list of notable addresses that are not globally reachable:
1540    /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified))
1541    /// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback))
1542    /// - IPv4-mapped addresses
1543    /// - Addresses reserved for benchmarking ([`is_benchmarking`](Ipv6Addr::is_benchmarking))
1544    /// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation))
1545    /// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local))
1546    /// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local))
1547    ///
1548    /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv6 Special-Purpose Address Registry].
1549    ///
1550    /// Note that an address having global scope is not the same as being globally reachable,
1551    /// and there is no direct relation between the two concepts: There exist addresses with global scope
1552    /// that are not globally reachable (for example unique local addresses),
1553    /// and addresses that are globally reachable without having global scope
1554    /// (multicast addresses with non-global scope).
1555    ///
1556    /// [IANA IPv6 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
1557    /// [unspecified address]: Ipv6Addr::UNSPECIFIED
1558    /// [loopback address]: Ipv6Addr::LOCALHOST
1559    ///
1560    /// # Examples
1561    ///
1562    /// ```
1563    /// #![feature(ip)]
1564    ///
1565    /// use std::net::Ipv6Addr;
1566    ///
1567    /// // Most IPv6 addresses are globally reachable:
1568    /// assert_eq!(Ipv6Addr::new(0x26, 0, 0x1c9, 0, 0, 0xafc8, 0x10, 0x1).is_global(), true);
1569    ///
1570    /// // However some addresses have been assigned a special meaning
1571    /// // that makes them not globally reachable. Some examples are:
1572    ///
1573    /// // The unspecified address (`::`)
1574    /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_global(), false);
1575    ///
1576    /// // The loopback address (`::1`)
1577    /// assert_eq!(Ipv6Addr::LOCALHOST.is_global(), false);
1578    ///
1579    /// // IPv4-mapped addresses (`::ffff:0:0/96`)
1580    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), false);
1581    ///
1582    /// // Addresses reserved for benchmarking (`2001:2::/48`)
1583    /// assert_eq!(Ipv6Addr::new(0x2001, 2, 0, 0, 0, 0, 0, 1,).is_global(), false);
1584    ///
1585    /// // Addresses reserved for documentation (`2001:db8::/32` and `3fff::/20`)
1586    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).is_global(), false);
1587    /// assert_eq!(Ipv6Addr::new(0x3fff, 0, 0, 0, 0, 0, 0, 0).is_global(), false);
1588    ///
1589    /// // Unique local addresses (`fc00::/7`)
1590    /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1591    ///
1592    /// // Unicast addresses with link-local scope (`fe80::/10`)
1593    /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1594    ///
1595    /// // For a complete overview see the IANA IPv6 Special-Purpose Address Registry.
1596    /// ```
1597    #[unstable(feature = "ip", issue = "27709")]
1598    #[must_use]
1599    #[inline]
1600    pub const fn is_global(&self) -> bool {
1601        !(self.is_unspecified()
1602            || self.is_loopback()
1603            // IPv4-mapped Address (`::ffff:0:0/96`)
1604            || matches!(self.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
1605            // IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
1606            || matches!(self.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
1607            // Discard-Only Address Block (`100::/64`)
1608            || matches!(self.segments(), [0x100, 0, 0, 0, _, _, _, _])
1609            // IETF Protocol Assignments (`2001::/23`)
1610            || (matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
1611                && !(
1612                    // Port Control Protocol Anycast (`2001:1::1`)
1613                    u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
1614                    // Traversal Using Relays around NAT Anycast (`2001:1::2`)
1615                    || u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
1616                    // AMT (`2001:3::/32`)
1617                    || matches!(self.segments(), [0x2001, 3, _, _, _, _, _, _])
1618                    // AS112-v6 (`2001:4:112::/48`)
1619                    || matches!(self.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
1620                    // ORCHIDv2 (`2001:20::/28`)
1621                    // Drone Remote ID Protocol Entity Tags (DETs) Prefix (`2001:30::/28`)`
1622                    || matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b >= 0x20 && b <= 0x3F)
1623                ))
1624            // 6to4 (`2002::/16`) – it's not explicitly documented as globally reachable,
1625            // IANA says N/A.
1626            || matches!(self.segments(), [0x2002, _, _, _, _, _, _, _])
1627            || self.is_documentation()
1628            // Segment Routing (SRv6) SIDs (`5f00::/16`)
1629            || matches!(self.segments(), [0x5f00, ..])
1630            || self.is_unique_local()
1631            || self.is_unicast_link_local())
1632    }
1633
1634    /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1635    ///
1636    /// This property is defined in [IETF RFC 4193].
1637    ///
1638    /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1639    ///
1640    /// # Examples
1641    ///
1642    /// ```
1643    /// use std::net::Ipv6Addr;
1644    ///
1645    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1646    /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1647    /// ```
1648    #[must_use]
1649    #[inline]
1650    #[stable(feature = "ipv6_is_unique_local", since = "1.84.0")]
1651    #[rustc_const_stable(feature = "ipv6_is_unique_local", since = "1.84.0")]
1652    pub const fn is_unique_local(&self) -> bool {
1653        (self.segments()[0] & 0xfe00) == 0xfc00
1654    }
1655
1656    /// Returns [`true`] if this is a unicast address, as defined by [IETF RFC 4291].
1657    /// Any address that is not a [multicast address] (`ff00::/8`) is unicast.
1658    ///
1659    /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1660    /// [multicast address]: Ipv6Addr::is_multicast
1661    ///
1662    /// # Examples
1663    ///
1664    /// ```
1665    /// #![feature(ip)]
1666    ///
1667    /// use std::net::Ipv6Addr;
1668    ///
1669    /// // The unspecified and loopback addresses are unicast.
1670    /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_unicast(), true);
1671    /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast(), true);
1672    ///
1673    /// // Any address that is not a multicast address (`ff00::/8`) is unicast.
1674    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast(), true);
1675    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_unicast(), false);
1676    /// ```
1677    #[unstable(feature = "ip", issue = "27709")]
1678    #[must_use]
1679    #[inline]
1680    pub const fn is_unicast(&self) -> bool {
1681        !self.is_multicast()
1682    }
1683
1684    /// Returns `true` if the address is a unicast address with link-local scope,
1685    /// as defined in [RFC 4291].
1686    ///
1687    /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
1688    /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
1689    /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
1690    ///
1691    /// ```text
1692    /// | 10 bits  |         54 bits         |          64 bits           |
1693    /// +----------+-------------------------+----------------------------+
1694    /// |1111111010|           0             |       interface ID         |
1695    /// +----------+-------------------------+----------------------------+
1696    /// ```
1697    /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
1698    /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
1699    /// and those addresses will have link-local scope.
1700    ///
1701    /// Also note that while [RFC 4291 section 2.5.3] mentions about the [loopback address] (`::1`) that "it is treated as having Link-Local scope",
1702    /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
1703    ///
1704    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
1705    /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1706    /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1707    /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1708    /// [loopback address]: Ipv6Addr::LOCALHOST
1709    ///
1710    /// # Examples
1711    ///
1712    /// ```
1713    /// use std::net::Ipv6Addr;
1714    ///
1715    /// // The loopback address (`::1`) does not actually have link-local scope.
1716    /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast_link_local(), false);
1717    ///
1718    /// // Only addresses in `fe80::/10` have link-local scope.
1719    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), false);
1720    /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1721    ///
1722    /// // Addresses outside the stricter `fe80::/64` also have link-local scope.
1723    /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0).is_unicast_link_local(), true);
1724    /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1725    /// ```
1726    #[must_use]
1727    #[inline]
1728    #[stable(feature = "ipv6_is_unique_local", since = "1.84.0")]
1729    #[rustc_const_stable(feature = "ipv6_is_unique_local", since = "1.84.0")]
1730    pub const fn is_unicast_link_local(&self) -> bool {
1731        (self.segments()[0] & 0xffc0) == 0xfe80
1732    }
1733
1734    /// Returns [`true`] if this is an address reserved for documentation
1735    /// (`2001:db8::/32` and `3fff::/20`).
1736    ///
1737    /// This property is defined by [IETF RFC 3849] and [IETF RFC 9637].
1738    ///
1739    /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1740    /// [IETF RFC 9637]: https://tools.ietf.org/html/rfc9637
1741    ///
1742    /// # Examples
1743    ///
1744    /// ```
1745    /// #![feature(ip)]
1746    ///
1747    /// use std::net::Ipv6Addr;
1748    ///
1749    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1750    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1751    /// assert_eq!(Ipv6Addr::new(0x3fff, 0, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1752    /// ```
1753    #[unstable(feature = "ip", issue = "27709")]
1754    #[must_use]
1755    #[inline]
1756    pub const fn is_documentation(&self) -> bool {
1757        matches!(self.segments(), [0x2001, 0xdb8, ..] | [0x3fff, 0..=0x0fff, ..])
1758    }
1759
1760    /// Returns [`true`] if this is an address reserved for benchmarking (`2001:2::/48`).
1761    ///
1762    /// This property is defined in [IETF RFC 5180], where it is mistakenly specified as covering the range `2001:0200::/48`.
1763    /// This is corrected in [IETF RFC Errata 1752] to `2001:0002::/48`.
1764    ///
1765    /// [IETF RFC 5180]: https://tools.ietf.org/html/rfc5180
1766    /// [IETF RFC Errata 1752]: https://www.rfc-editor.org/errata_search.php?eid=1752
1767    ///
1768    /// ```
1769    /// #![feature(ip)]
1770    ///
1771    /// use std::net::Ipv6Addr;
1772    ///
1773    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc613, 0x0).is_benchmarking(), false);
1774    /// assert_eq!(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0).is_benchmarking(), true);
1775    /// ```
1776    #[unstable(feature = "ip", issue = "27709")]
1777    #[must_use]
1778    #[inline]
1779    pub const fn is_benchmarking(&self) -> bool {
1780        (self.segments()[0] == 0x2001) && (self.segments()[1] == 0x2) && (self.segments()[2] == 0)
1781    }
1782
1783    /// Returns [`true`] if the address is a globally routable unicast address.
1784    ///
1785    /// The following return false:
1786    ///
1787    /// - the loopback address
1788    /// - the link-local addresses
1789    /// - unique local addresses
1790    /// - the unspecified address
1791    /// - the address range reserved for documentation
1792    ///
1793    /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1794    ///
1795    /// ```no_rust
1796    /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1797    /// be supported in new implementations (i.e., new implementations must treat this prefix as
1798    /// Global Unicast).
1799    /// ```
1800    ///
1801    /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1802    ///
1803    /// # Examples
1804    ///
1805    /// ```
1806    /// #![feature(ip)]
1807    ///
1808    /// use std::net::Ipv6Addr;
1809    ///
1810    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1811    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1812    /// ```
1813    #[unstable(feature = "ip", issue = "27709")]
1814    #[must_use]
1815    #[inline]
1816    pub const fn is_unicast_global(&self) -> bool {
1817        self.is_unicast()
1818            && !self.is_loopback()
1819            && !self.is_unicast_link_local()
1820            && !self.is_unique_local()
1821            && !self.is_unspecified()
1822            && !self.is_documentation()
1823            && !self.is_benchmarking()
1824    }
1825
1826    /// Returns the address's multicast scope if the address is multicast.
1827    ///
1828    /// # Examples
1829    ///
1830    /// ```
1831    /// #![feature(ip)]
1832    ///
1833    /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1834    ///
1835    /// assert_eq!(
1836    ///     Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1837    ///     Some(Ipv6MulticastScope::Global)
1838    /// );
1839    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1840    /// ```
1841    #[unstable(feature = "ip", issue = "27709")]
1842    #[must_use]
1843    #[inline]
1844    pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1845        if self.is_multicast() {
1846            match self.segments()[0] & 0x000f {
1847                1 => Some(Ipv6MulticastScope::InterfaceLocal),
1848                2 => Some(Ipv6MulticastScope::LinkLocal),
1849                3 => Some(Ipv6MulticastScope::RealmLocal),
1850                4 => Some(Ipv6MulticastScope::AdminLocal),
1851                5 => Some(Ipv6MulticastScope::SiteLocal),
1852                8 => Some(Ipv6MulticastScope::OrganizationLocal),
1853                14 => Some(Ipv6MulticastScope::Global),
1854                _ => None,
1855            }
1856        } else {
1857            None
1858        }
1859    }
1860
1861    /// Returns [`true`] if this is a multicast address (`ff00::/8`).
1862    ///
1863    /// This property is defined by [IETF RFC 4291].
1864    ///
1865    /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1866    ///
1867    /// # Examples
1868    ///
1869    /// ```
1870    /// use std::net::Ipv6Addr;
1871    ///
1872    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1873    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1874    /// ```
1875    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1876    #[stable(since = "1.7.0", feature = "ip_17")]
1877    #[must_use]
1878    #[inline]
1879    pub const fn is_multicast(&self) -> bool {
1880        (self.segments()[0] & 0xff00) == 0xff00
1881    }
1882
1883    /// Returns [`true`] if the address is an IPv4-mapped address (`::ffff:0:0/96`).
1884    ///
1885    /// IPv4-mapped addresses can be converted to their canonical IPv4 address with
1886    /// [`to_ipv4_mapped`](Ipv6Addr::to_ipv4_mapped).
1887    ///
1888    /// # Examples
1889    /// ```
1890    /// #![feature(ip)]
1891    ///
1892    /// use std::net::{Ipv4Addr, Ipv6Addr};
1893    ///
1894    /// let ipv4_mapped = Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped();
1895    /// assert_eq!(ipv4_mapped.is_ipv4_mapped(), true);
1896    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff).is_ipv4_mapped(), true);
1897    ///
1898    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_ipv4_mapped(), false);
1899    /// ```
1900    #[unstable(feature = "ip", issue = "27709")]
1901    #[must_use]
1902    #[inline]
1903    pub const fn is_ipv4_mapped(&self) -> bool {
1904        matches!(self.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
1905    }
1906
1907    /// Converts this address to an [`IPv4` address] if it's an [IPv4-mapped] address,
1908    /// as defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1909    ///
1910    /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1911    /// All addresses *not* starting with `::ffff` will return `None`.
1912    ///
1913    /// [`IPv4` address]: Ipv4Addr
1914    /// [IPv4-mapped]: Ipv6Addr
1915    /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1916    ///
1917    /// # Examples
1918    ///
1919    /// ```
1920    /// use std::net::{Ipv4Addr, Ipv6Addr};
1921    ///
1922    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1923    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1924    ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1925    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1926    /// ```
1927    #[inline]
1928    #[must_use = "this returns the result of the operation, \
1929                  without modifying the original"]
1930    #[stable(feature = "ipv6_to_ipv4_mapped", since = "1.63.0")]
1931    #[rustc_const_stable(feature = "const_ipv6_to_ipv4_mapped", since = "1.75.0")]
1932    pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1933        match self.octets() {
1934            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1935                Some(Ipv4Addr::new(a, b, c, d))
1936            }
1937            _ => None,
1938        }
1939    }
1940
1941    /// Converts this address to an [`IPv4` address] if it is either
1942    /// an [IPv4-compatible] address as defined in [IETF RFC 4291 section 2.5.5.1],
1943    /// or an [IPv4-mapped] address as defined in [IETF RFC 4291 section 2.5.5.2],
1944    /// otherwise returns [`None`].
1945    ///
1946    /// Note that this will return an [`IPv4` address] for the IPv6 loopback address `::1`. Use
1947    /// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
1948    ///
1949    /// `::a.b.c.d` and `::ffff:a.b.c.d` become `a.b.c.d`. `::1` becomes `0.0.0.1`.
1950    /// All addresses *not* starting with either all zeroes or `::ffff` will return `None`.
1951    ///
1952    /// [`IPv4` address]: Ipv4Addr
1953    /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
1954    /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
1955    /// [IETF RFC 4291 section 2.5.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.5.1
1956    /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1957    ///
1958    /// # Examples
1959    ///
1960    /// ```
1961    /// use std::net::{Ipv4Addr, Ipv6Addr};
1962    ///
1963    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1964    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1965    ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1966    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1967    ///            Some(Ipv4Addr::new(0, 0, 0, 1)));
1968    /// ```
1969    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1970    #[stable(feature = "rust1", since = "1.0.0")]
1971    #[must_use = "this returns the result of the operation, \
1972                  without modifying the original"]
1973    #[inline]
1974    pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1975        if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1976            let [a, b] = ab.to_be_bytes();
1977            let [c, d] = cd.to_be_bytes();
1978            Some(Ipv4Addr::new(a, b, c, d))
1979        } else {
1980            None
1981        }
1982    }
1983
1984    /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped address,
1985    /// otherwise returns self wrapped in an `IpAddr::V6`.
1986    ///
1987    /// # Examples
1988    ///
1989    /// ```
1990    /// use std::net::Ipv6Addr;
1991    ///
1992    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).is_loopback(), false);
1993    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).to_canonical().is_loopback(), true);
1994    /// ```
1995    #[inline]
1996    #[must_use = "this returns the result of the operation, \
1997                  without modifying the original"]
1998    #[stable(feature = "ip_to_canonical", since = "1.75.0")]
1999    #[rustc_const_stable(feature = "ip_to_canonical", since = "1.75.0")]
2000    pub const fn to_canonical(&self) -> IpAddr {
2001        if let Some(mapped) = self.to_ipv4_mapped() {
2002            return IpAddr::V4(mapped);
2003        }
2004        IpAddr::V6(*self)
2005    }
2006
2007    /// Returns the sixteen eight-bit integers the IPv6 address consists of.
2008    ///
2009    /// ```
2010    /// use std::net::Ipv6Addr;
2011    ///
2012    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
2013    ///            [0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
2014    /// ```
2015    #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
2016    #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
2017    #[must_use]
2018    #[inline]
2019    pub const fn octets(&self) -> [u8; 16] {
2020        self.octets
2021    }
2022
2023    /// Creates an `Ipv6Addr` from a sixteen element byte array.
2024    ///
2025    /// # Examples
2026    ///
2027    /// ```
2028    /// #![feature(ip_from)]
2029    /// use std::net::Ipv6Addr;
2030    ///
2031    /// let addr = Ipv6Addr::from_octets([
2032    ///     0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,
2033    ///     0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,
2034    /// ]);
2035    /// assert_eq!(
2036    ///     Ipv6Addr::new(
2037    ///         0x1918, 0x1716, 0x1514, 0x1312,
2038    ///         0x1110, 0x0f0e, 0x0d0c, 0x0b0a,
2039    ///     ),
2040    ///     addr
2041    /// );
2042    /// ```
2043    #[unstable(feature = "ip_from", issue = "131360")]
2044    #[must_use]
2045    #[inline]
2046    pub const fn from_octets(octets: [u8; 16]) -> Ipv6Addr {
2047        Ipv6Addr { octets }
2048    }
2049
2050    /// Returns the sixteen eight-bit integers the IPv6 address consists of
2051    /// as a slice.
2052    ///
2053    /// # Examples
2054    ///
2055    /// ```
2056    /// #![feature(ip_as_octets)]
2057    ///
2058    /// use std::net::Ipv6Addr;
2059    ///
2060    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).as_octets(),
2061    ///            &[255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
2062    /// ```
2063    #[unstable(feature = "ip_as_octets", issue = "137259")]
2064    #[inline]
2065    pub const fn as_octets(&self) -> &[u8; 16] {
2066        &self.octets
2067    }
2068}
2069
2070/// Writes an Ipv6Addr, conforming to the canonical style described by
2071/// [RFC 5952](https://tools.ietf.org/html/rfc5952).
2072#[stable(feature = "rust1", since = "1.0.0")]
2073impl fmt::Display for Ipv6Addr {
2074    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2075        // If there are no alignment requirements, write the IP address directly to `f`.
2076        // Otherwise, write it to a local buffer and then use `f.pad`.
2077        if f.precision().is_none() && f.width().is_none() {
2078            let segments = self.segments();
2079
2080            if let Some(ipv4) = self.to_ipv4_mapped() {
2081                write!(f, "::ffff:{}", ipv4)
2082            } else {
2083                #[derive(Copy, Clone, Default)]
2084                struct Span {
2085                    start: usize,
2086                    len: usize,
2087                }
2088
2089                // Find the inner 0 span
2090                let zeroes = {
2091                    let mut longest = Span::default();
2092                    let mut current = Span::default();
2093
2094                    for (i, &segment) in segments.iter().enumerate() {
2095                        if segment == 0 {
2096                            if current.len == 0 {
2097                                current.start = i;
2098                            }
2099
2100                            current.len += 1;
2101
2102                            if current.len > longest.len {
2103                                longest = current;
2104                            }
2105                        } else {
2106                            current = Span::default();
2107                        }
2108                    }
2109
2110                    longest
2111                };
2112
2113                /// Writes a colon-separated part of the address.
2114                #[inline]
2115                fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
2116                    if let Some((first, tail)) = chunk.split_first() {
2117                        write!(f, "{:x}", first)?;
2118                        for segment in tail {
2119                            f.write_char(':')?;
2120                            write!(f, "{:x}", segment)?;
2121                        }
2122                    }
2123                    Ok(())
2124                }
2125
2126                if zeroes.len > 1 {
2127                    fmt_subslice(f, &segments[..zeroes.start])?;
2128                    f.write_str("::")?;
2129                    fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
2130                } else {
2131                    fmt_subslice(f, &segments)
2132                }
2133            }
2134        } else {
2135            const LONGEST_IPV6_ADDR: &str = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
2136
2137            let mut buf = DisplayBuffer::<{ LONGEST_IPV6_ADDR.len() }>::new();
2138            // Buffer is long enough for the longest possible IPv6 address, so this should never fail.
2139            write!(buf, "{}", self).unwrap();
2140
2141            f.pad(buf.as_str())
2142        }
2143    }
2144}
2145
2146#[stable(feature = "rust1", since = "1.0.0")]
2147impl fmt::Debug for Ipv6Addr {
2148    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2149        fmt::Display::fmt(self, fmt)
2150    }
2151}
2152
2153#[stable(feature = "ip_cmp", since = "1.16.0")]
2154impl PartialEq<IpAddr> for Ipv6Addr {
2155    #[inline]
2156    fn eq(&self, other: &IpAddr) -> bool {
2157        match other {
2158            IpAddr::V4(_) => false,
2159            IpAddr::V6(v6) => self == v6,
2160        }
2161    }
2162}
2163
2164#[stable(feature = "ip_cmp", since = "1.16.0")]
2165impl PartialEq<Ipv6Addr> for IpAddr {
2166    #[inline]
2167    fn eq(&self, other: &Ipv6Addr) -> bool {
2168        match self {
2169            IpAddr::V4(_) => false,
2170            IpAddr::V6(v6) => v6 == other,
2171        }
2172    }
2173}
2174
2175#[stable(feature = "rust1", since = "1.0.0")]
2176impl PartialOrd for Ipv6Addr {
2177    #[inline]
2178    fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
2179        Some(self.cmp(other))
2180    }
2181}
2182
2183#[stable(feature = "ip_cmp", since = "1.16.0")]
2184impl PartialOrd<Ipv6Addr> for IpAddr {
2185    #[inline]
2186    fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
2187        match self {
2188            IpAddr::V4(_) => Some(Ordering::Less),
2189            IpAddr::V6(v6) => v6.partial_cmp(other),
2190        }
2191    }
2192}
2193
2194#[stable(feature = "ip_cmp", since = "1.16.0")]
2195impl PartialOrd<IpAddr> for Ipv6Addr {
2196    #[inline]
2197    fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
2198        match other {
2199            IpAddr::V4(_) => Some(Ordering::Greater),
2200            IpAddr::V6(v6) => self.partial_cmp(v6),
2201        }
2202    }
2203}
2204
2205#[stable(feature = "rust1", since = "1.0.0")]
2206impl Ord for Ipv6Addr {
2207    #[inline]
2208    fn cmp(&self, other: &Ipv6Addr) -> Ordering {
2209        self.segments().cmp(&other.segments())
2210    }
2211}
2212
2213#[stable(feature = "i128", since = "1.26.0")]
2214impl From<Ipv6Addr> for u128 {
2215    /// Uses [`Ipv6Addr::to_bits`] to convert an IPv6 address to a host byte order `u128`.
2216    #[inline]
2217    fn from(ip: Ipv6Addr) -> u128 {
2218        ip.to_bits()
2219    }
2220}
2221#[stable(feature = "i128", since = "1.26.0")]
2222impl From<u128> for Ipv6Addr {
2223    /// Uses [`Ipv6Addr::from_bits`] to convert a host byte order `u128` to an IPv6 address.
2224    #[inline]
2225    fn from(ip: u128) -> Ipv6Addr {
2226        Ipv6Addr::from_bits(ip)
2227    }
2228}
2229
2230#[stable(feature = "ipv6_from_octets", since = "1.9.0")]
2231impl From<[u8; 16]> for Ipv6Addr {
2232    /// Creates an `Ipv6Addr` from a sixteen element byte array.
2233    ///
2234    /// # Examples
2235    ///
2236    /// ```
2237    /// use std::net::Ipv6Addr;
2238    ///
2239    /// let addr = Ipv6Addr::from([
2240    ///     0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,
2241    ///     0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,
2242    /// ]);
2243    /// assert_eq!(
2244    ///     Ipv6Addr::new(
2245    ///         0x1918, 0x1716, 0x1514, 0x1312,
2246    ///         0x1110, 0x0f0e, 0x0d0c, 0x0b0a,
2247    ///     ),
2248    ///     addr
2249    /// );
2250    /// ```
2251    #[inline]
2252    fn from(octets: [u8; 16]) -> Ipv6Addr {
2253        Ipv6Addr { octets }
2254    }
2255}
2256
2257#[stable(feature = "ipv6_from_segments", since = "1.16.0")]
2258impl From<[u16; 8]> for Ipv6Addr {
2259    /// Creates an `Ipv6Addr` from an eight element 16-bit array.
2260    ///
2261    /// # Examples
2262    ///
2263    /// ```
2264    /// use std::net::Ipv6Addr;
2265    ///
2266    /// let addr = Ipv6Addr::from([
2267    ///     0x20du16, 0x20cu16, 0x20bu16, 0x20au16,
2268    ///     0x209u16, 0x208u16, 0x207u16, 0x206u16,
2269    /// ]);
2270    /// assert_eq!(
2271    ///     Ipv6Addr::new(
2272    ///         0x20d, 0x20c, 0x20b, 0x20a,
2273    ///         0x209, 0x208, 0x207, 0x206,
2274    ///     ),
2275    ///     addr
2276    /// );
2277    /// ```
2278    #[inline]
2279    fn from(segments: [u16; 8]) -> Ipv6Addr {
2280        let [a, b, c, d, e, f, g, h] = segments;
2281        Ipv6Addr::new(a, b, c, d, e, f, g, h)
2282    }
2283}
2284
2285#[stable(feature = "ip_from_slice", since = "1.17.0")]
2286impl From<[u8; 16]> for IpAddr {
2287    /// Creates an `IpAddr::V6` from a sixteen element byte array.
2288    ///
2289    /// # Examples
2290    ///
2291    /// ```
2292    /// use std::net::{IpAddr, Ipv6Addr};
2293    ///
2294    /// let addr = IpAddr::from([
2295    ///     0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,
2296    ///     0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,
2297    /// ]);
2298    /// assert_eq!(
2299    ///     IpAddr::V6(Ipv6Addr::new(
2300    ///         0x1918, 0x1716, 0x1514, 0x1312,
2301    ///         0x1110, 0x0f0e, 0x0d0c, 0x0b0a,
2302    ///     )),
2303    ///     addr
2304    /// );
2305    /// ```
2306    #[inline]
2307    fn from(octets: [u8; 16]) -> IpAddr {
2308        IpAddr::V6(Ipv6Addr::from(octets))
2309    }
2310}
2311
2312#[stable(feature = "ip_from_slice", since = "1.17.0")]
2313impl From<[u16; 8]> for IpAddr {
2314    /// Creates an `IpAddr::V6` from an eight element 16-bit array.
2315    ///
2316    /// # Examples
2317    ///
2318    /// ```
2319    /// use std::net::{IpAddr, Ipv6Addr};
2320    ///
2321    /// let addr = IpAddr::from([
2322    ///     0x20du16, 0x20cu16, 0x20bu16, 0x20au16,
2323    ///     0x209u16, 0x208u16, 0x207u16, 0x206u16,
2324    /// ]);
2325    /// assert_eq!(
2326    ///     IpAddr::V6(Ipv6Addr::new(
2327    ///         0x20d, 0x20c, 0x20b, 0x20a,
2328    ///         0x209, 0x208, 0x207, 0x206,
2329    ///     )),
2330    ///     addr
2331    /// );
2332    /// ```
2333    #[inline]
2334    fn from(segments: [u16; 8]) -> IpAddr {
2335        IpAddr::V6(Ipv6Addr::from(segments))
2336    }
2337}
2338
2339#[stable(feature = "ip_bitops", since = "1.75.0")]
2340impl Not for Ipv4Addr {
2341    type Output = Ipv4Addr;
2342
2343    #[inline]
2344    fn not(mut self) -> Ipv4Addr {
2345        for octet in &mut self.octets {
2346            *octet = !*octet;
2347        }
2348        self
2349    }
2350}
2351
2352#[stable(feature = "ip_bitops", since = "1.75.0")]
2353impl Not for &'_ Ipv4Addr {
2354    type Output = Ipv4Addr;
2355
2356    #[inline]
2357    fn not(self) -> Ipv4Addr {
2358        !*self
2359    }
2360}
2361
2362#[stable(feature = "ip_bitops", since = "1.75.0")]
2363impl Not for Ipv6Addr {
2364    type Output = Ipv6Addr;
2365
2366    #[inline]
2367    fn not(mut self) -> Ipv6Addr {
2368        for octet in &mut self.octets {
2369            *octet = !*octet;
2370        }
2371        self
2372    }
2373}
2374
2375#[stable(feature = "ip_bitops", since = "1.75.0")]
2376impl Not for &'_ Ipv6Addr {
2377    type Output = Ipv6Addr;
2378
2379    #[inline]
2380    fn not(self) -> Ipv6Addr {
2381        !*self
2382    }
2383}
2384
2385macro_rules! bitop_impls {
2386    ($(
2387        $(#[$attr:meta])*
2388        impl ($BitOp:ident, $BitOpAssign:ident) for $ty:ty = ($bitop:ident, $bitop_assign:ident);
2389    )*) => {
2390        $(
2391            $(#[$attr])*
2392            impl $BitOpAssign for $ty {
2393                fn $bitop_assign(&mut self, rhs: $ty) {
2394                    for (lhs, rhs) in iter::zip(&mut self.octets, rhs.octets) {
2395                        lhs.$bitop_assign(rhs);
2396                    }
2397                }
2398            }
2399
2400            $(#[$attr])*
2401            impl $BitOpAssign<&'_ $ty> for $ty {
2402                fn $bitop_assign(&mut self, rhs: &'_ $ty) {
2403                    self.$bitop_assign(*rhs);
2404                }
2405            }
2406
2407            $(#[$attr])*
2408            impl $BitOp for $ty {
2409                type Output = $ty;
2410
2411                #[inline]
2412                fn $bitop(mut self, rhs: $ty) -> $ty {
2413                    self.$bitop_assign(rhs);
2414                    self
2415                }
2416            }
2417
2418            $(#[$attr])*
2419            impl $BitOp<&'_ $ty> for $ty {
2420                type Output = $ty;
2421
2422                #[inline]
2423                fn $bitop(mut self, rhs: &'_ $ty) -> $ty {
2424                    self.$bitop_assign(*rhs);
2425                    self
2426                }
2427            }
2428
2429            $(#[$attr])*
2430            impl $BitOp<$ty> for &'_ $ty {
2431                type Output = $ty;
2432
2433                #[inline]
2434                fn $bitop(self, rhs: $ty) -> $ty {
2435                    let mut lhs = *self;
2436                    lhs.$bitop_assign(rhs);
2437                    lhs
2438                }
2439            }
2440
2441            $(#[$attr])*
2442            impl $BitOp<&'_ $ty> for &'_ $ty {
2443                type Output = $ty;
2444
2445                #[inline]
2446                fn $bitop(self, rhs: &'_ $ty) -> $ty {
2447                    let mut lhs = *self;
2448                    lhs.$bitop_assign(*rhs);
2449                    lhs
2450                }
2451            }
2452        )*
2453    };
2454}
2455
2456bitop_impls! {
2457    #[stable(feature = "ip_bitops", since = "1.75.0")]
2458    impl (BitAnd, BitAndAssign) for Ipv4Addr = (bitand, bitand_assign);
2459    #[stable(feature = "ip_bitops", since = "1.75.0")]
2460    impl (BitOr, BitOrAssign) for Ipv4Addr = (bitor, bitor_assign);
2461
2462    #[stable(feature = "ip_bitops", since = "1.75.0")]
2463    impl (BitAnd, BitAndAssign) for Ipv6Addr = (bitand, bitand_assign);
2464    #[stable(feature = "ip_bitops", since = "1.75.0")]
2465    impl (BitOr, BitOrAssign) for Ipv6Addr = (bitor, bitor_assign);
2466}