Skip to main content

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