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            || self.is_documentation()
929            || self.is_benchmarking()
930            || self.is_reserved()
931            || self.is_broadcast())
932    }
933
934    /// Returns [`true`] if this address is part of the Shared Address Space defined in
935    /// [IETF RFC 6598] (`100.64.0.0/10`).
936    ///
937    /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
938    ///
939    /// # Examples
940    ///
941    /// ```
942    /// #![feature(ip)]
943    /// use std::net::Ipv4Addr;
944    ///
945    /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
946    /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
947    /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
948    /// ```
949    #[unstable(feature = "ip", issue = "27709")]
950    #[must_use]
951    #[inline]
952    pub const fn is_shared(&self) -> bool {
953        self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
954    }
955
956    /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
957    /// network devices benchmarking.
958    ///
959    /// This range is defined in [IETF RFC 2544] as `192.18.0.0` through
960    /// `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
961    ///
962    /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
963    /// [errata 423]: https://www.rfc-editor.org/errata/eid423
964    ///
965    /// # Examples
966    ///
967    /// ```
968    /// #![feature(ip)]
969    /// use std::net::Ipv4Addr;
970    ///
971    /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
972    /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
973    /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
974    /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
975    /// ```
976    #[unstable(feature = "ip", issue = "27709")]
977    #[must_use]
978    #[inline]
979    pub const fn is_benchmarking(&self) -> bool {
980        self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
981    }
982
983    /// Returns [`true`] if this address is reserved by IANA for future use.
984    ///
985    /// [IETF RFC 1112] defines the block of reserved addresses as `240.0.0.0/4`.
986    /// This range normally includes the broadcast address `255.255.255.255`, but
987    /// this implementation explicitly excludes it, since it is obviously not
988    /// reserved for future use.
989    ///
990    /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
991    ///
992    /// # Warning
993    ///
994    /// As IANA assigns new addresses, this method will be
995    /// updated. This may result in non-reserved addresses being
996    /// treated as reserved in code that relies on an outdated version
997    /// of this method.
998    ///
999    /// # Examples
1000    ///
1001    /// ```
1002    /// #![feature(ip)]
1003    /// use std::net::Ipv4Addr;
1004    ///
1005    /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
1006    /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
1007    ///
1008    /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
1009    /// // The broadcast address is not considered as reserved for future use by this implementation
1010    /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
1011    /// ```
1012    #[unstable(feature = "ip", issue = "27709")]
1013    #[must_use]
1014    #[inline]
1015    pub const fn is_reserved(&self) -> bool {
1016        self.octets()[0] & 240 == 240 && !self.is_broadcast()
1017    }
1018
1019    /// Returns [`true`] if this is a multicast address (`224.0.0.0/4`).
1020    ///
1021    /// Multicast addresses have a most significant octet between `224` and `239`,
1022    /// and is defined by [IETF RFC 5771].
1023    ///
1024    /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
1025    ///
1026    /// # Examples
1027    ///
1028    /// ```
1029    /// use std::net::Ipv4Addr;
1030    ///
1031    /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
1032    /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
1033    /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
1034    /// ```
1035    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1036    #[stable(since = "1.7.0", feature = "ip_17")]
1037    #[must_use]
1038    #[inline]
1039    pub const fn is_multicast(&self) -> bool {
1040        self.octets()[0] >= 224 && self.octets()[0] <= 239
1041    }
1042
1043    /// Returns [`true`] if this is a broadcast address (`255.255.255.255`).
1044    ///
1045    /// A broadcast address has all octets set to `255` as defined in [IETF RFC 919].
1046    ///
1047    /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
1048    ///
1049    /// # Examples
1050    ///
1051    /// ```
1052    /// use std::net::Ipv4Addr;
1053    ///
1054    /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
1055    /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
1056    /// ```
1057    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1058    #[stable(since = "1.7.0", feature = "ip_17")]
1059    #[must_use]
1060    #[inline]
1061    pub const fn is_broadcast(&self) -> bool {
1062        u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
1063    }
1064
1065    /// Returns [`true`] if this address is in a range designated for documentation.
1066    ///
1067    /// This is defined in [IETF RFC 5737]:
1068    ///
1069    /// - `192.0.2.0/24` (TEST-NET-1)
1070    /// - `198.51.100.0/24` (TEST-NET-2)
1071    /// - `203.0.113.0/24` (TEST-NET-3)
1072    ///
1073    /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
1074    ///
1075    /// # Examples
1076    ///
1077    /// ```
1078    /// use std::net::Ipv4Addr;
1079    ///
1080    /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
1081    /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
1082    /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
1083    /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
1084    /// ```
1085    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1086    #[stable(since = "1.7.0", feature = "ip_17")]
1087    #[must_use]
1088    #[inline]
1089    pub const fn is_documentation(&self) -> bool {
1090        matches!(self.octets(), [192, 0, 2, _] | [198, 51, 100, _] | [203, 0, 113, _])
1091    }
1092
1093    /// Converts this address to an [IPv4-compatible] [`IPv6` address].
1094    ///
1095    /// `a.b.c.d` becomes `::a.b.c.d`
1096    ///
1097    /// Note that IPv4-compatible addresses have been officially deprecated.
1098    /// If you don't explicitly need an IPv4-compatible address for legacy reasons, consider using `to_ipv6_mapped` instead.
1099    ///
1100    /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
1101    /// [`IPv6` address]: Ipv6Addr
1102    ///
1103    /// # Examples
1104    ///
1105    /// ```
1106    /// use std::net::{Ipv4Addr, Ipv6Addr};
1107    ///
1108    /// assert_eq!(
1109    ///     Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
1110    ///     Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x2ff)
1111    /// );
1112    /// ```
1113    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1114    #[stable(feature = "rust1", since = "1.0.0")]
1115    #[must_use = "this returns the result of the operation, \
1116                  without modifying the original"]
1117    #[inline]
1118    pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
1119        let [a, b, c, d] = self.octets();
1120        Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] }
1121    }
1122
1123    /// Converts this address to an [IPv4-mapped] [`IPv6` address].
1124    ///
1125    /// `a.b.c.d` becomes `::ffff:a.b.c.d`
1126    ///
1127    /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
1128    /// [`IPv6` address]: Ipv6Addr
1129    ///
1130    /// # Examples
1131    ///
1132    /// ```
1133    /// use std::net::{Ipv4Addr, Ipv6Addr};
1134    ///
1135    /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
1136    ///            Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff));
1137    /// ```
1138    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1139    #[stable(feature = "rust1", since = "1.0.0")]
1140    #[must_use = "this returns the result of the operation, \
1141                  without modifying the original"]
1142    #[inline]
1143    pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
1144        let [a, b, c, d] = self.octets();
1145        Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] }
1146    }
1147}
1148
1149#[stable(feature = "ip_addr", since = "1.7.0")]
1150impl fmt::Display for IpAddr {
1151    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1152        match self {
1153            IpAddr::V4(ip) => ip.fmt(fmt),
1154            IpAddr::V6(ip) => ip.fmt(fmt),
1155        }
1156    }
1157}
1158
1159#[stable(feature = "ip_addr", since = "1.7.0")]
1160impl fmt::Debug for IpAddr {
1161    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1162        fmt::Display::fmt(self, fmt)
1163    }
1164}
1165
1166#[stable(feature = "ip_from_ip", since = "1.16.0")]
1167#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1168const impl From<Ipv4Addr> for IpAddr {
1169    /// Copies this address to a new `IpAddr::V4`.
1170    ///
1171    /// # Examples
1172    ///
1173    /// ```
1174    /// use std::net::{IpAddr, Ipv4Addr};
1175    ///
1176    /// let addr = Ipv4Addr::new(127, 0, 0, 1);
1177    ///
1178    /// assert_eq!(
1179    ///     IpAddr::V4(addr),
1180    ///     IpAddr::from(addr)
1181    /// )
1182    /// ```
1183    #[inline]
1184    fn from(ipv4: Ipv4Addr) -> IpAddr {
1185        IpAddr::V4(ipv4)
1186    }
1187}
1188
1189#[stable(feature = "ip_from_ip", since = "1.16.0")]
1190#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1191const impl From<Ipv6Addr> for IpAddr {
1192    /// Copies this address to a new `IpAddr::V6`.
1193    ///
1194    /// # Examples
1195    ///
1196    /// ```
1197    /// use std::net::{IpAddr, Ipv6Addr};
1198    ///
1199    /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1200    ///
1201    /// assert_eq!(
1202    ///     IpAddr::V6(addr),
1203    ///     IpAddr::from(addr)
1204    /// );
1205    /// ```
1206    #[inline]
1207    fn from(ipv6: Ipv6Addr) -> IpAddr {
1208        IpAddr::V6(ipv6)
1209    }
1210}
1211
1212#[stable(feature = "rust1", since = "1.0.0")]
1213impl fmt::Display for Ipv4Addr {
1214    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1215        let octets = self.octets();
1216
1217        // If there are no alignment requirements, write the IP address directly to `f`.
1218        // Otherwise, write it to a local buffer and then use `f.pad`.
1219        if fmt.precision().is_none() && fmt.width().is_none() {
1220            write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
1221        } else {
1222            const LONGEST_IPV4_ADDR: &str = "255.255.255.255";
1223
1224            let mut buf = DisplayBuffer::buffer::<{ LONGEST_IPV4_ADDR.len() }>();
1225            let mut buf = DisplayBuffer::new(&mut buf);
1226            // Buffer is long enough for the longest possible IPv4 address, so this should never fail.
1227            write!(buf, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
1228
1229            fmt.pad(buf.as_str())
1230        }
1231    }
1232}
1233
1234#[stable(feature = "rust1", since = "1.0.0")]
1235impl fmt::Debug for Ipv4Addr {
1236    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1237        fmt::Display::fmt(self, fmt)
1238    }
1239}
1240
1241#[stable(feature = "ip_cmp", since = "1.16.0")]
1242impl PartialEq<Ipv4Addr> for IpAddr {
1243    #[inline]
1244    fn eq(&self, other: &Ipv4Addr) -> bool {
1245        match self {
1246            IpAddr::V4(v4) => v4 == other,
1247            IpAddr::V6(_) => false,
1248        }
1249    }
1250}
1251
1252#[stable(feature = "ip_cmp", since = "1.16.0")]
1253impl PartialEq<IpAddr> for Ipv4Addr {
1254    #[inline]
1255    fn eq(&self, other: &IpAddr) -> bool {
1256        match other {
1257            IpAddr::V4(v4) => self == v4,
1258            IpAddr::V6(_) => false,
1259        }
1260    }
1261}
1262
1263#[stable(feature = "rust1", since = "1.0.0")]
1264#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1265const impl PartialOrd for Ipv4Addr {
1266    #[inline]
1267    fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1268        Some(self.cmp(other))
1269    }
1270}
1271
1272#[stable(feature = "ip_cmp", since = "1.16.0")]
1273impl PartialOrd<Ipv4Addr> for IpAddr {
1274    #[inline]
1275    fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1276        match self {
1277            IpAddr::V4(v4) => v4.partial_cmp(other),
1278            IpAddr::V6(_) => Some(Ordering::Greater),
1279        }
1280    }
1281}
1282
1283#[stable(feature = "ip_cmp", since = "1.16.0")]
1284impl PartialOrd<IpAddr> for Ipv4Addr {
1285    #[inline]
1286    fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1287        match other {
1288            IpAddr::V4(v4) => self.partial_cmp(v4),
1289            IpAddr::V6(_) => Some(Ordering::Less),
1290        }
1291    }
1292}
1293
1294#[stable(feature = "rust1", since = "1.0.0")]
1295#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1296const impl Ord for Ipv4Addr {
1297    #[inline]
1298    fn cmp(&self, other: &Ipv4Addr) -> Ordering {
1299        self.octets.cmp(&other.octets)
1300    }
1301}
1302
1303#[stable(feature = "ip_u32", since = "1.1.0")]
1304#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1305const impl From<Ipv4Addr> for u32 {
1306    /// Uses [`Ipv4Addr::to_bits`] to convert an IPv4 address to a host byte order `u32`.
1307    #[inline]
1308    fn from(ip: Ipv4Addr) -> u32 {
1309        ip.to_bits()
1310    }
1311}
1312
1313#[stable(feature = "ip_u32", since = "1.1.0")]
1314#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1315const impl From<u32> for Ipv4Addr {
1316    /// Uses [`Ipv4Addr::from_bits`] to convert a host byte order `u32` into an IPv4 address.
1317    #[inline]
1318    fn from(ip: u32) -> Ipv4Addr {
1319        Ipv4Addr::from_bits(ip)
1320    }
1321}
1322
1323#[stable(feature = "from_slice_v4", since = "1.9.0")]
1324#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1325const impl From<[u8; 4]> for Ipv4Addr {
1326    /// Creates an `Ipv4Addr` from a four element byte array.
1327    ///
1328    /// # Examples
1329    ///
1330    /// ```
1331    /// use std::net::Ipv4Addr;
1332    ///
1333    /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1334    /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1335    /// ```
1336    #[inline]
1337    fn from(octets: [u8; 4]) -> Ipv4Addr {
1338        Ipv4Addr { octets }
1339    }
1340}
1341
1342#[stable(feature = "ip_from_slice", since = "1.17.0")]
1343#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1344const impl From<[u8; 4]> for IpAddr {
1345    /// Creates an `IpAddr::V4` from a four element byte array.
1346    ///
1347    /// # Examples
1348    ///
1349    /// ```
1350    /// use std::net::{IpAddr, Ipv4Addr};
1351    ///
1352    /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1353    /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1354    /// ```
1355    #[inline]
1356    fn from(octets: [u8; 4]) -> IpAddr {
1357        IpAddr::V4(Ipv4Addr::from(octets))
1358    }
1359}
1360
1361impl Ipv6Addr {
1362    /// Creates a new IPv6 address from eight 16-bit segments.
1363    ///
1364    /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1365    ///
1366    /// # Examples
1367    ///
1368    /// ```
1369    /// use std::net::Ipv6Addr;
1370    ///
1371    /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1372    /// ```
1373    #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
1374    #[stable(feature = "rust1", since = "1.0.0")]
1375    #[must_use]
1376    #[inline]
1377    pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1378        let addr16 = [
1379            a.to_be(),
1380            b.to_be(),
1381            c.to_be(),
1382            d.to_be(),
1383            e.to_be(),
1384            f.to_be(),
1385            g.to_be(),
1386            h.to_be(),
1387        ];
1388        Ipv6Addr {
1389            // All elements in `addr16` are big endian.
1390            // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1391            octets: unsafe { transmute::<_, [u8; 16]>(addr16) },
1392        }
1393    }
1394
1395    /// The size of an IPv6 address in bits.
1396    ///
1397    /// # Examples
1398    ///
1399    /// ```
1400    /// use std::net::Ipv6Addr;
1401    ///
1402    /// assert_eq!(Ipv6Addr::BITS, 128);
1403    /// ```
1404    #[stable(feature = "ip_bits", since = "1.80.0")]
1405    pub const BITS: u32 = 128;
1406
1407    /// Converts an IPv6 address into a `u128` representation using native byte order.
1408    ///
1409    /// Although IPv6 addresses are big-endian, the `u128` value will use the target platform's
1410    /// native byte order. That is, the `u128` value is an integer representation of the IPv6
1411    /// address and not an integer interpretation of the IPv6 address's big-endian bitstring. This
1412    /// means that the `u128` value masked with `0xffffffffffffffffffffffffffff0000_u128` will set
1413    /// the last segment in the address to 0, regardless of the target platform's endianness.
1414    ///
1415    /// # Examples
1416    ///
1417    /// ```
1418    /// use std::net::Ipv6Addr;
1419    ///
1420    /// let addr = Ipv6Addr::new(
1421    ///     0x1020, 0x3040, 0x5060, 0x7080,
1422    ///     0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1423    /// );
1424    /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, addr.to_bits());
1425    /// ```
1426    ///
1427    /// ```
1428    /// use std::net::Ipv6Addr;
1429    ///
1430    /// let addr = Ipv6Addr::new(
1431    ///     0x1020, 0x3040, 0x5060, 0x7080,
1432    ///     0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1433    /// );
1434    /// let addr_bits = addr.to_bits() & 0xffffffffffffffffffffffffffff0000_u128;
1435    /// assert_eq!(
1436    ///     Ipv6Addr::new(
1437    ///         0x1020, 0x3040, 0x5060, 0x7080,
1438    ///         0x90A0, 0xB0C0, 0xD0E0, 0x0000,
1439    ///     ),
1440    ///     Ipv6Addr::from_bits(addr_bits));
1441    ///
1442    /// ```
1443    #[rustc_const_stable(feature = "ip_bits", since = "1.80.0")]
1444    #[stable(feature = "ip_bits", since = "1.80.0")]
1445    #[must_use]
1446    #[inline]
1447    pub const fn to_bits(self) -> u128 {
1448        u128::from_be_bytes(self.octets)
1449    }
1450
1451    /// Converts a native byte order `u128` into an IPv6 address.
1452    ///
1453    /// See [`Ipv6Addr::to_bits`] for an explanation on endianness.
1454    ///
1455    /// # Examples
1456    ///
1457    /// ```
1458    /// use std::net::Ipv6Addr;
1459    ///
1460    /// let addr = Ipv6Addr::from_bits(0x102030405060708090A0B0C0D0E0F00D_u128);
1461    /// assert_eq!(
1462    ///     Ipv6Addr::new(
1463    ///         0x1020, 0x3040, 0x5060, 0x7080,
1464    ///         0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1465    ///     ),
1466    ///     addr);
1467    /// ```
1468    #[rustc_const_stable(feature = "ip_bits", since = "1.80.0")]
1469    #[stable(feature = "ip_bits", since = "1.80.0")]
1470    #[must_use]
1471    #[inline]
1472    pub const fn from_bits(bits: u128) -> Ipv6Addr {
1473        Ipv6Addr { octets: bits.to_be_bytes() }
1474    }
1475
1476    /// An IPv6 address representing localhost: `::1`.
1477    ///
1478    /// This corresponds to constant `IN6ADDR_LOOPBACK_INIT` or `in6addr_loopback` in other
1479    /// languages.
1480    ///
1481    /// # Examples
1482    ///
1483    /// ```
1484    /// use std::net::Ipv6Addr;
1485    ///
1486    /// let addr = Ipv6Addr::LOCALHOST;
1487    /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1488    /// ```
1489    #[doc(alias = "IN6ADDR_LOOPBACK_INIT")]
1490    #[doc(alias = "in6addr_loopback")]
1491    #[stable(feature = "ip_constructors", since = "1.30.0")]
1492    pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1493
1494    /// An IPv6 address representing the unspecified address: `::`.
1495    ///
1496    /// This corresponds to constant `IN6ADDR_ANY_INIT` or `in6addr_any` in other languages.
1497    ///
1498    /// # Examples
1499    ///
1500    /// ```
1501    /// use std::net::Ipv6Addr;
1502    ///
1503    /// let addr = Ipv6Addr::UNSPECIFIED;
1504    /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1505    /// ```
1506    #[doc(alias = "IN6ADDR_ANY_INIT")]
1507    #[doc(alias = "in6addr_any")]
1508    #[stable(feature = "ip_constructors", since = "1.30.0")]
1509    pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1510
1511    /// Returns the eight 16-bit segments that make up this address.
1512    ///
1513    /// # Examples
1514    ///
1515    /// ```
1516    /// use std::net::Ipv6Addr;
1517    ///
1518    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1519    ///            [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1520    /// ```
1521    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1522    #[stable(feature = "rust1", since = "1.0.0")]
1523    #[must_use]
1524    #[inline]
1525    pub const fn segments(&self) -> [u16; 8] {
1526        // All elements in `self.octets` must be big endian.
1527        // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1528        let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.octets) };
1529        // We want native endian u16
1530        [
1531            u16::from_be(a),
1532            u16::from_be(b),
1533            u16::from_be(c),
1534            u16::from_be(d),
1535            u16::from_be(e),
1536            u16::from_be(f),
1537            u16::from_be(g),
1538            u16::from_be(h),
1539        ]
1540    }
1541
1542    /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1543    ///
1544    /// # Examples
1545    ///
1546    /// ```
1547    /// use std::net::Ipv6Addr;
1548    ///
1549    /// let addr = Ipv6Addr::from_segments([
1550    ///     0x20du16, 0x20cu16, 0x20bu16, 0x20au16,
1551    ///     0x209u16, 0x208u16, 0x207u16, 0x206u16,
1552    /// ]);
1553    /// assert_eq!(
1554    ///     Ipv6Addr::new(
1555    ///         0x20d, 0x20c, 0x20b, 0x20a,
1556    ///         0x209, 0x208, 0x207, 0x206,
1557    ///     ),
1558    ///     addr
1559    /// );
1560    /// ```
1561    #[stable(feature = "ip_from", since = "1.91.0")]
1562    #[rustc_const_stable(feature = "ip_from", since = "1.91.0")]
1563    #[must_use]
1564    #[inline]
1565    pub const fn from_segments(segments: [u16; 8]) -> Ipv6Addr {
1566        let [a, b, c, d, e, f, g, h] = segments;
1567        Ipv6Addr::new(a, b, c, d, e, f, g, h)
1568    }
1569
1570    /// Returns [`true`] for the special 'unspecified' address (`::`).
1571    ///
1572    /// This property is defined in [IETF RFC 4291].
1573    ///
1574    /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1575    ///
1576    /// # Examples
1577    ///
1578    /// ```
1579    /// use std::net::Ipv6Addr;
1580    ///
1581    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1582    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1583    /// ```
1584    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1585    #[stable(since = "1.7.0", feature = "ip_17")]
1586    #[must_use]
1587    #[inline]
1588    pub const fn is_unspecified(&self) -> bool {
1589        u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1590    }
1591
1592    /// Returns [`true`] if this is the [loopback address] (`::1`),
1593    /// as defined in [IETF RFC 4291 section 2.5.3].
1594    ///
1595    /// Contrary to IPv4, in IPv6 there is only one loopback address.
1596    ///
1597    /// [loopback address]: Ipv6Addr::LOCALHOST
1598    /// [IETF RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1599    ///
1600    /// # Examples
1601    ///
1602    /// ```
1603    /// use std::net::Ipv6Addr;
1604    ///
1605    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1606    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1607    /// ```
1608    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1609    #[stable(since = "1.7.0", feature = "ip_17")]
1610    #[must_use]
1611    #[inline]
1612    pub const fn is_loopback(&self) -> bool {
1613        u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1614    }
1615
1616    /// Returns [`true`] if the address appears to be globally reachable
1617    /// as specified by the [IANA IPv6 Special-Purpose Address Registry].
1618    ///
1619    /// Whether or not an address is practically reachable will depend on your
1620    /// network configuration. Most IPv6 addresses are globally reachable, unless
1621    /// they are specifically defined as *not* globally reachable.
1622    ///
1623    /// Non-exhaustive list of notable addresses that are not globally reachable:
1624    /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified))
1625    /// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback))
1626    /// - IPv4-mapped addresses
1627    /// - Addresses reserved for benchmarking ([`is_benchmarking`](Ipv6Addr::is_benchmarking))
1628    /// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation))
1629    /// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local))
1630    /// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local))
1631    ///
1632    /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv6 Special-Purpose Address Registry].
1633    ///
1634    /// Note that an address having global scope is not the same as being globally reachable,
1635    /// and there is no direct relation between the two concepts: There exist addresses with global scope
1636    /// that are not globally reachable (for example unique local addresses),
1637    /// and addresses that are globally reachable without having global scope
1638    /// (multicast addresses with non-global scope).
1639    ///
1640    /// [IANA IPv6 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
1641    /// [unspecified address]: Ipv6Addr::UNSPECIFIED
1642    /// [loopback address]: Ipv6Addr::LOCALHOST
1643    ///
1644    /// # Examples
1645    ///
1646    /// ```
1647    /// #![feature(ip)]
1648    ///
1649    /// use std::net::Ipv6Addr;
1650    ///
1651    /// // Most IPv6 addresses are globally reachable:
1652    /// assert_eq!(Ipv6Addr::new(0x26, 0, 0x1c9, 0, 0, 0xafc8, 0x10, 0x1).is_global(), true);
1653    ///
1654    /// // However some addresses have been assigned a special meaning
1655    /// // that makes them not globally reachable. Some examples are:
1656    ///
1657    /// // The unspecified address (`::`)
1658    /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_global(), false);
1659    ///
1660    /// // The loopback address (`::1`)
1661    /// assert_eq!(Ipv6Addr::LOCALHOST.is_global(), false);
1662    ///
1663    /// // IPv4-mapped addresses (`::ffff:0:0/96`)
1664    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), false);
1665    ///
1666    /// // Addresses reserved for benchmarking (`2001:2::/48`)
1667    /// assert_eq!(Ipv6Addr::new(0x2001, 2, 0, 0, 0, 0, 0, 1,).is_global(), false);
1668    ///
1669    /// // Addresses reserved for documentation (`2001:db8::/32` and `3fff::/20`)
1670    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).is_global(), false);
1671    /// assert_eq!(Ipv6Addr::new(0x3fff, 0, 0, 0, 0, 0, 0, 0).is_global(), false);
1672    ///
1673    /// // Unique local addresses (`fc00::/7`)
1674    /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1675    ///
1676    /// // Unicast addresses with link-local scope (`fe80::/10`)
1677    /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1678    ///
1679    /// // For a complete overview see the IANA IPv6 Special-Purpose Address Registry.
1680    /// ```
1681    #[unstable(feature = "ip", issue = "27709")]
1682    #[must_use]
1683    #[inline]
1684    pub const fn is_global(&self) -> bool {
1685        !(self.is_unspecified()
1686            || self.is_loopback()
1687            // IPv4-mapped Address (`::ffff:0:0/96`)
1688            || matches!(self.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
1689            // IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
1690            || matches!(self.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
1691            // Discard-Only Address Block (`100::/64`)
1692            || matches!(self.segments(), [0x100, 0, 0, 0, _, _, _, _])
1693            // IETF Protocol Assignments (`2001::/23`)
1694            || (matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
1695                && !(
1696                    // Port Control Protocol Anycast (`2001:1::1`)
1697                    u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
1698                    // Traversal Using Relays around NAT Anycast (`2001:1::2`)
1699                    || u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
1700                    // AMT (`2001:3::/32`)
1701                    || matches!(self.segments(), [0x2001, 3, _, _, _, _, _, _])
1702                    // AS112-v6 (`2001:4:112::/48`)
1703                    || matches!(self.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
1704                    // ORCHIDv2 (`2001:20::/28`)
1705                    // Drone Remote ID Protocol Entity Tags (DETs) Prefix (`2001:30::/28`)`
1706                    || matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b >= 0x20 && b <= 0x3F)
1707                ))
1708            // 6to4 (`2002::/16`) – it's not explicitly documented as globally reachable,
1709            // IANA says N/A.
1710            || matches!(self.segments(), [0x2002, _, _, _, _, _, _, _])
1711            || self.is_documentation()
1712            // Segment Routing (SRv6) SIDs (`5f00::/16`)
1713            || matches!(self.segments(), [0x5f00, ..])
1714            || self.is_unique_local()
1715            || self.is_unicast_link_local())
1716    }
1717
1718    /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1719    ///
1720    /// This property is defined in [IETF RFC 4193].
1721    ///
1722    /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1723    ///
1724    /// # Examples
1725    ///
1726    /// ```
1727    /// use std::net::Ipv6Addr;
1728    ///
1729    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1730    /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1731    /// ```
1732    #[must_use]
1733    #[inline]
1734    #[stable(feature = "ipv6_is_unique_local", since = "1.84.0")]
1735    #[rustc_const_stable(feature = "ipv6_is_unique_local", since = "1.84.0")]
1736    pub const fn is_unique_local(&self) -> bool {
1737        (self.segments()[0] & 0xfe00) == 0xfc00
1738    }
1739
1740    /// Returns [`true`] if this is a unicast address, as defined by [IETF RFC 4291].
1741    /// Any address that is not a [multicast address] (`ff00::/8`) is unicast.
1742    ///
1743    /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1744    /// [multicast address]: Ipv6Addr::is_multicast
1745    ///
1746    /// # Examples
1747    ///
1748    /// ```
1749    /// #![feature(ip)]
1750    ///
1751    /// use std::net::Ipv6Addr;
1752    ///
1753    /// // The unspecified and loopback addresses are unicast.
1754    /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_unicast(), true);
1755    /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast(), true);
1756    ///
1757    /// // Any address that is not a multicast address (`ff00::/8`) is unicast.
1758    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast(), true);
1759    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_unicast(), false);
1760    /// ```
1761    #[unstable(feature = "ip", issue = "27709")]
1762    #[must_use]
1763    #[inline]
1764    pub const fn is_unicast(&self) -> bool {
1765        !self.is_multicast()
1766    }
1767
1768    /// Returns `true` if the address is a unicast address with link-local scope,
1769    /// as defined in [RFC 4291].
1770    ///
1771    /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
1772    /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
1773    /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
1774    ///
1775    /// ```text
1776    /// | 10 bits  |         54 bits         |          64 bits           |
1777    /// +----------+-------------------------+----------------------------+
1778    /// |1111111010|           0             |       interface ID         |
1779    /// +----------+-------------------------+----------------------------+
1780    /// ```
1781    /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
1782    /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
1783    /// and those addresses will have link-local scope.
1784    ///
1785    /// 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",
1786    /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
1787    ///
1788    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
1789    /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1790    /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1791    /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1792    /// [loopback address]: Ipv6Addr::LOCALHOST
1793    ///
1794    /// # Examples
1795    ///
1796    /// ```
1797    /// use std::net::Ipv6Addr;
1798    ///
1799    /// // The loopback address (`::1`) does not actually have link-local scope.
1800    /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast_link_local(), false);
1801    ///
1802    /// // Only addresses in `fe80::/10` have link-local scope.
1803    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), false);
1804    /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1805    ///
1806    /// // Addresses outside the stricter `fe80::/64` also have link-local scope.
1807    /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0).is_unicast_link_local(), true);
1808    /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1809    /// ```
1810    #[must_use]
1811    #[inline]
1812    #[stable(feature = "ipv6_is_unique_local", since = "1.84.0")]
1813    #[rustc_const_stable(feature = "ipv6_is_unique_local", since = "1.84.0")]
1814    pub const fn is_unicast_link_local(&self) -> bool {
1815        (self.segments()[0] & 0xffc0) == 0xfe80
1816    }
1817
1818    /// Returns [`true`] if this is an address reserved for documentation
1819    /// (`2001:db8::/32` and `3fff::/20`).
1820    ///
1821    /// This property is defined by [IETF RFC 3849] and [IETF RFC 9637].
1822    ///
1823    /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1824    /// [IETF RFC 9637]: https://tools.ietf.org/html/rfc9637
1825    ///
1826    /// # Examples
1827    ///
1828    /// ```
1829    /// #![feature(ip)]
1830    ///
1831    /// use std::net::Ipv6Addr;
1832    ///
1833    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1834    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1835    /// assert_eq!(Ipv6Addr::new(0x3fff, 0, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1836    /// ```
1837    #[unstable(feature = "ip", issue = "27709")]
1838    #[must_use]
1839    #[inline]
1840    pub const fn is_documentation(&self) -> bool {
1841        matches!(self.segments(), [0x2001, 0xdb8, ..] | [0x3fff, 0..=0x0fff, ..])
1842    }
1843
1844    /// Returns [`true`] if this is an address reserved for benchmarking (`2001:2::/48`).
1845    ///
1846    /// This property is defined in [IETF RFC 5180], where it is mistakenly specified as covering the range `2001:0200::/48`.
1847    /// This is corrected in [IETF RFC Errata 1752] to `2001:0002::/48`.
1848    ///
1849    /// [IETF RFC 5180]: https://tools.ietf.org/html/rfc5180
1850    /// [IETF RFC Errata 1752]: https://www.rfc-editor.org/errata_search.php?eid=1752
1851    ///
1852    /// ```
1853    /// #![feature(ip)]
1854    ///
1855    /// use std::net::Ipv6Addr;
1856    ///
1857    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc613, 0x0).is_benchmarking(), false);
1858    /// assert_eq!(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0).is_benchmarking(), true);
1859    /// ```
1860    #[unstable(feature = "ip", issue = "27709")]
1861    #[must_use]
1862    #[inline]
1863    pub const fn is_benchmarking(&self) -> bool {
1864        (self.segments()[0] == 0x2001) && (self.segments()[1] == 0x2) && (self.segments()[2] == 0)
1865    }
1866
1867    /// Returns [`true`] if the address is a globally routable unicast address.
1868    ///
1869    /// The following return false:
1870    ///
1871    /// - the loopback address
1872    /// - the link-local addresses
1873    /// - unique local addresses
1874    /// - the unspecified address
1875    /// - the address range reserved for documentation
1876    ///
1877    /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1878    ///
1879    /// ```no_rust
1880    /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1881    /// be supported in new implementations (i.e., new implementations must treat this prefix as
1882    /// Global Unicast).
1883    /// ```
1884    ///
1885    /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1886    ///
1887    /// # Examples
1888    ///
1889    /// ```
1890    /// #![feature(ip)]
1891    ///
1892    /// use std::net::Ipv6Addr;
1893    ///
1894    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1895    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1896    /// ```
1897    #[unstable(feature = "ip", issue = "27709")]
1898    #[must_use]
1899    #[inline]
1900    pub const fn is_unicast_global(&self) -> bool {
1901        self.is_unicast()
1902            && !self.is_loopback()
1903            && !self.is_unicast_link_local()
1904            && !self.is_unique_local()
1905            && !self.is_unspecified()
1906            && !self.is_documentation()
1907            && !self.is_benchmarking()
1908    }
1909
1910    /// Returns the address's multicast scope if the address is multicast.
1911    ///
1912    /// # Examples
1913    ///
1914    /// ```
1915    /// #![feature(ip)]
1916    ///
1917    /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1918    ///
1919    /// assert_eq!(
1920    ///     Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1921    ///     Some(Ipv6MulticastScope::Global)
1922    /// );
1923    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1924    /// ```
1925    #[unstable(feature = "ip", issue = "27709")]
1926    #[must_use]
1927    #[inline]
1928    pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1929        if self.is_multicast() {
1930            match self.segments()[0] & 0x000f {
1931                0x0 => Some(Ipv6MulticastScope::Reserved0),
1932                0x1 => Some(Ipv6MulticastScope::InterfaceLocal),
1933                0x2 => Some(Ipv6MulticastScope::LinkLocal),
1934                0x3 => Some(Ipv6MulticastScope::RealmLocal),
1935                0x4 => Some(Ipv6MulticastScope::AdminLocal),
1936                0x5 => Some(Ipv6MulticastScope::SiteLocal),
1937                0x6 => Some(Ipv6MulticastScope::Unassigned6),
1938                0x7 => Some(Ipv6MulticastScope::Unassigned7),
1939                0x8 => Some(Ipv6MulticastScope::OrganizationLocal),
1940                0x9 => Some(Ipv6MulticastScope::Unassigned9),
1941                0xA => Some(Ipv6MulticastScope::UnassignedA),
1942                0xB => Some(Ipv6MulticastScope::UnassignedB),
1943                0xC => Some(Ipv6MulticastScope::UnassignedC),
1944                0xD => Some(Ipv6MulticastScope::UnassignedD),
1945                0xE => Some(Ipv6MulticastScope::Global),
1946                0xF => Some(Ipv6MulticastScope::ReservedF),
1947                _ => unreachable!(),
1948            }
1949        } else {
1950            None
1951        }
1952    }
1953
1954    /// Returns [`true`] if this is a multicast address (`ff00::/8`).
1955    ///
1956    /// This property is defined by [IETF RFC 4291].
1957    ///
1958    /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1959    ///
1960    /// # Examples
1961    ///
1962    /// ```
1963    /// use std::net::Ipv6Addr;
1964    ///
1965    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1966    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1967    /// ```
1968    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1969    #[stable(since = "1.7.0", feature = "ip_17")]
1970    #[must_use]
1971    #[inline]
1972    pub const fn is_multicast(&self) -> bool {
1973        (self.segments()[0] & 0xff00) == 0xff00
1974    }
1975
1976    /// Returns [`true`] if the address is an IPv4-mapped address (`::ffff:0:0/96`).
1977    ///
1978    /// IPv4-mapped addresses can be converted to their canonical IPv4 address with
1979    /// [`to_ipv4_mapped`](Ipv6Addr::to_ipv4_mapped).
1980    ///
1981    /// # Examples
1982    /// ```
1983    /// #![feature(ip)]
1984    ///
1985    /// use std::net::{Ipv4Addr, Ipv6Addr};
1986    ///
1987    /// let ipv4_mapped = Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped();
1988    /// assert_eq!(ipv4_mapped.is_ipv4_mapped(), true);
1989    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff).is_ipv4_mapped(), true);
1990    ///
1991    /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_ipv4_mapped(), false);
1992    /// ```
1993    #[unstable(feature = "ip", issue = "27709")]
1994    #[must_use]
1995    #[inline]
1996    pub const fn is_ipv4_mapped(&self) -> bool {
1997        matches!(self.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
1998    }
1999
2000    /// Converts this address to an [`IPv4` address] if it's an [IPv4-mapped] address,
2001    /// as defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
2002    ///
2003    /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
2004    /// All addresses *not* starting with `::ffff` will return `None`.
2005    ///
2006    /// [`IPv4` address]: Ipv4Addr
2007    /// [IPv4-mapped]: Ipv6Addr
2008    /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
2009    ///
2010    /// # Examples
2011    ///
2012    /// ```
2013    /// use std::net::{Ipv4Addr, Ipv6Addr};
2014    ///
2015    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
2016    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
2017    ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
2018    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
2019    /// ```
2020    #[inline]
2021    #[must_use = "this returns the result of the operation, \
2022                  without modifying the original"]
2023    #[stable(feature = "ipv6_to_ipv4_mapped", since = "1.63.0")]
2024    #[rustc_const_stable(feature = "const_ipv6_to_ipv4_mapped", since = "1.75.0")]
2025    pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
2026        match self.octets() {
2027            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
2028                Some(Ipv4Addr::new(a, b, c, d))
2029            }
2030            _ => None,
2031        }
2032    }
2033
2034    /// Converts this address to an [`IPv4` address] if it is either
2035    /// an [IPv4-compatible] address as defined in [IETF RFC 4291 section 2.5.5.1],
2036    /// or an [IPv4-mapped] address as defined in [IETF RFC 4291 section 2.5.5.2],
2037    /// otherwise returns [`None`].
2038    ///
2039    /// Note that this will return an [`IPv4` address] for the IPv6 loopback address `::1`. Use
2040    /// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
2041    ///
2042    /// `::a.b.c.d` and `::ffff:a.b.c.d` become `a.b.c.d`. `::1` becomes `0.0.0.1`.
2043    /// All addresses *not* starting with either all zeroes or `::ffff` will return `None`.
2044    ///
2045    /// [`IPv4` address]: Ipv4Addr
2046    /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
2047    /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
2048    /// [IETF RFC 4291 section 2.5.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.5.1
2049    /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
2050    ///
2051    /// # Examples
2052    ///
2053    /// ```
2054    /// use std::net::{Ipv4Addr, Ipv6Addr};
2055    ///
2056    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
2057    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
2058    ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
2059    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
2060    ///            Some(Ipv4Addr::new(0, 0, 0, 1)));
2061    /// ```
2062    #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
2063    #[stable(feature = "rust1", since = "1.0.0")]
2064    #[must_use = "this returns the result of the operation, \
2065                  without modifying the original"]
2066    #[inline]
2067    pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
2068        if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
2069            let [a, b] = ab.to_be_bytes();
2070            let [c, d] = cd.to_be_bytes();
2071            Some(Ipv4Addr::new(a, b, c, d))
2072        } else {
2073            None
2074        }
2075    }
2076
2077    /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped address,
2078    /// otherwise returns self wrapped in an `IpAddr::V6`.
2079    ///
2080    /// # Examples
2081    ///
2082    /// ```
2083    /// use std::net::Ipv6Addr;
2084    ///
2085    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).is_loopback(), false);
2086    /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).to_canonical().is_loopback(), true);
2087    /// ```
2088    #[inline]
2089    #[must_use = "this returns the result of the operation, \
2090                  without modifying the original"]
2091    #[stable(feature = "ip_to_canonical", since = "1.75.0")]
2092    #[rustc_const_stable(feature = "ip_to_canonical", since = "1.75.0")]
2093    pub const fn to_canonical(&self) -> IpAddr {
2094        if let Some(mapped) = self.to_ipv4_mapped() {
2095            return IpAddr::V4(mapped);
2096        }
2097        IpAddr::V6(*self)
2098    }
2099
2100    /// Returns the sixteen eight-bit integers the IPv6 address consists of.
2101    ///
2102    /// ```
2103    /// use std::net::Ipv6Addr;
2104    ///
2105    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
2106    ///            [0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
2107    /// ```
2108    #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
2109    #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
2110    #[must_use]
2111    #[inline]
2112    pub const fn octets(&self) -> [u8; 16] {
2113        self.octets
2114    }
2115
2116    /// Creates an `Ipv6Addr` from a sixteen element byte array.
2117    ///
2118    /// # Examples
2119    ///
2120    /// ```
2121    /// use std::net::Ipv6Addr;
2122    ///
2123    /// let addr = Ipv6Addr::from_octets([
2124    ///     0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,
2125    ///     0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,
2126    /// ]);
2127    /// assert_eq!(
2128    ///     Ipv6Addr::new(
2129    ///         0x1918, 0x1716, 0x1514, 0x1312,
2130    ///         0x1110, 0x0f0e, 0x0d0c, 0x0b0a,
2131    ///     ),
2132    ///     addr
2133    /// );
2134    /// ```
2135    #[stable(feature = "ip_from", since = "1.91.0")]
2136    #[rustc_const_stable(feature = "ip_from", since = "1.91.0")]
2137    #[must_use]
2138    #[inline]
2139    pub const fn from_octets(octets: [u8; 16]) -> Ipv6Addr {
2140        Ipv6Addr { octets }
2141    }
2142
2143    /// Returns the sixteen eight-bit integers the IPv6 address consists of
2144    /// as a slice.
2145    ///
2146    /// # Examples
2147    ///
2148    /// ```
2149    /// #![feature(ip_as_octets)]
2150    ///
2151    /// use std::net::Ipv6Addr;
2152    ///
2153    /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).as_octets(),
2154    ///            &[255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
2155    /// ```
2156    #[unstable(feature = "ip_as_octets", issue = "137259")]
2157    #[inline]
2158    pub const fn as_octets(&self) -> &[u8; 16] {
2159        &self.octets
2160    }
2161}
2162
2163/// Writes an Ipv6Addr, conforming to the canonical style described by
2164/// [RFC 5952](https://tools.ietf.org/html/rfc5952).
2165#[stable(feature = "rust1", since = "1.0.0")]
2166impl fmt::Display for Ipv6Addr {
2167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2168        // If there are no alignment requirements, write the IP address directly to `f`.
2169        // Otherwise, write it to a local buffer and then use `f.pad`.
2170        if f.precision().is_none() && f.width().is_none() {
2171            let segments = self.segments();
2172
2173            if let Some(ipv4) = self.to_ipv4_mapped() {
2174                write!(f, "::ffff:{}", ipv4)
2175            } else {
2176                #[derive(Copy, Clone, Default)]
2177                struct Span {
2178                    start: usize,
2179                    len: usize,
2180                }
2181
2182                // Find the inner 0 span
2183                let zeroes = {
2184                    let mut longest = Span::default();
2185                    let mut current = Span::default();
2186
2187                    for (i, &segment) in segments.iter().enumerate() {
2188                        if segment == 0 {
2189                            if current.len == 0 {
2190                                current.start = i;
2191                            }
2192
2193                            current.len += 1;
2194
2195                            if current.len > longest.len {
2196                                longest = current;
2197                            }
2198                        } else {
2199                            current = Span::default();
2200                        }
2201                    }
2202
2203                    longest
2204                };
2205
2206                /// Writes a colon-separated part of the address.
2207                #[inline]
2208                fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
2209                    if let Some((first, tail)) = chunk.split_first() {
2210                        write!(f, "{:x}", first)?;
2211                        for segment in tail {
2212                            f.write_char(':')?;
2213                            write!(f, "{:x}", segment)?;
2214                        }
2215                    }
2216                    Ok(())
2217                }
2218
2219                if zeroes.len > 1 {
2220                    fmt_subslice(f, &segments[..zeroes.start])?;
2221                    f.write_str("::")?;
2222                    fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
2223                } else {
2224                    fmt_subslice(f, &segments)
2225                }
2226            }
2227        } else {
2228            const LONGEST_IPV6_ADDR: &str = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
2229
2230            let mut buf = DisplayBuffer::buffer::<{ LONGEST_IPV6_ADDR.len() }>();
2231            let mut buf = DisplayBuffer::new(&mut buf);
2232            // Buffer is long enough for the longest possible IPv6 address, so this should never fail.
2233            write!(buf, "{}", self).unwrap();
2234
2235            f.pad(buf.as_str())
2236        }
2237    }
2238}
2239
2240#[stable(feature = "rust1", since = "1.0.0")]
2241impl fmt::Debug for Ipv6Addr {
2242    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2243        fmt::Display::fmt(self, fmt)
2244    }
2245}
2246
2247#[stable(feature = "ip_cmp", since = "1.16.0")]
2248impl PartialEq<IpAddr> for Ipv6Addr {
2249    #[inline]
2250    fn eq(&self, other: &IpAddr) -> bool {
2251        match other {
2252            IpAddr::V4(_) => false,
2253            IpAddr::V6(v6) => self == v6,
2254        }
2255    }
2256}
2257
2258#[stable(feature = "ip_cmp", since = "1.16.0")]
2259impl PartialEq<Ipv6Addr> for IpAddr {
2260    #[inline]
2261    fn eq(&self, other: &Ipv6Addr) -> bool {
2262        match self {
2263            IpAddr::V4(_) => false,
2264            IpAddr::V6(v6) => v6 == other,
2265        }
2266    }
2267}
2268
2269#[stable(feature = "rust1", since = "1.0.0")]
2270#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2271const impl PartialOrd for Ipv6Addr {
2272    #[inline]
2273    fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
2274        Some(self.cmp(other))
2275    }
2276}
2277
2278#[stable(feature = "ip_cmp", since = "1.16.0")]
2279impl PartialOrd<Ipv6Addr> for IpAddr {
2280    #[inline]
2281    fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
2282        match self {
2283            IpAddr::V4(_) => Some(Ordering::Less),
2284            IpAddr::V6(v6) => v6.partial_cmp(other),
2285        }
2286    }
2287}
2288
2289#[stable(feature = "ip_cmp", since = "1.16.0")]
2290impl PartialOrd<IpAddr> for Ipv6Addr {
2291    #[inline]
2292    fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
2293        match other {
2294            IpAddr::V4(_) => Some(Ordering::Greater),
2295            IpAddr::V6(v6) => self.partial_cmp(v6),
2296        }
2297    }
2298}
2299
2300#[stable(feature = "rust1", since = "1.0.0")]
2301#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2302const impl Ord for Ipv6Addr {
2303    #[inline]
2304    fn cmp(&self, other: &Ipv6Addr) -> Ordering {
2305        self.segments().cmp(&other.segments())
2306    }
2307}
2308
2309#[stable(feature = "i128", since = "1.26.0")]
2310#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2311const impl From<Ipv6Addr> for u128 {
2312    /// Uses [`Ipv6Addr::to_bits`] to convert an IPv6 address to a host byte order `u128`.
2313    #[inline]
2314    fn from(ip: Ipv6Addr) -> u128 {
2315        ip.to_bits()
2316    }
2317}
2318#[stable(feature = "i128", since = "1.26.0")]
2319#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2320const impl From<u128> for Ipv6Addr {
2321    /// Uses [`Ipv6Addr::from_bits`] to convert a host byte order `u128` to an IPv6 address.
2322    #[inline]
2323    fn from(ip: u128) -> Ipv6Addr {
2324        Ipv6Addr::from_bits(ip)
2325    }
2326}
2327
2328#[stable(feature = "ipv6_from_octets", since = "1.9.0")]
2329#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2330const impl From<[u8; 16]> for Ipv6Addr {
2331    /// Creates an `Ipv6Addr` from a sixteen element byte array.
2332    ///
2333    /// # Examples
2334    ///
2335    /// ```
2336    /// use std::net::Ipv6Addr;
2337    ///
2338    /// let addr = Ipv6Addr::from([
2339    ///     0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,
2340    ///     0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,
2341    /// ]);
2342    /// assert_eq!(
2343    ///     Ipv6Addr::new(
2344    ///         0x1918, 0x1716, 0x1514, 0x1312,
2345    ///         0x1110, 0x0f0e, 0x0d0c, 0x0b0a,
2346    ///     ),
2347    ///     addr
2348    /// );
2349    /// ```
2350    #[inline]
2351    fn from(octets: [u8; 16]) -> Ipv6Addr {
2352        Ipv6Addr { octets }
2353    }
2354}
2355
2356#[stable(feature = "ipv6_from_segments", since = "1.16.0")]
2357#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2358const impl From<[u16; 8]> for Ipv6Addr {
2359    /// Creates an `Ipv6Addr` from an eight element 16-bit array.
2360    ///
2361    /// # Examples
2362    ///
2363    /// ```
2364    /// use std::net::Ipv6Addr;
2365    ///
2366    /// let addr = Ipv6Addr::from([
2367    ///     0x20du16, 0x20cu16, 0x20bu16, 0x20au16,
2368    ///     0x209u16, 0x208u16, 0x207u16, 0x206u16,
2369    /// ]);
2370    /// assert_eq!(
2371    ///     Ipv6Addr::new(
2372    ///         0x20d, 0x20c, 0x20b, 0x20a,
2373    ///         0x209, 0x208, 0x207, 0x206,
2374    ///     ),
2375    ///     addr
2376    /// );
2377    /// ```
2378    #[inline]
2379    fn from(segments: [u16; 8]) -> Ipv6Addr {
2380        let [a, b, c, d, e, f, g, h] = segments;
2381        Ipv6Addr::new(a, b, c, d, e, f, g, h)
2382    }
2383}
2384
2385#[stable(feature = "ip_from_slice", since = "1.17.0")]
2386#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2387const impl From<[u8; 16]> for IpAddr {
2388    /// Creates an `IpAddr::V6` from a sixteen element byte array.
2389    ///
2390    /// # Examples
2391    ///
2392    /// ```
2393    /// use std::net::{IpAddr, Ipv6Addr};
2394    ///
2395    /// let addr = IpAddr::from([
2396    ///     0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,
2397    ///     0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,
2398    /// ]);
2399    /// assert_eq!(
2400    ///     IpAddr::V6(Ipv6Addr::new(
2401    ///         0x1918, 0x1716, 0x1514, 0x1312,
2402    ///         0x1110, 0x0f0e, 0x0d0c, 0x0b0a,
2403    ///     )),
2404    ///     addr
2405    /// );
2406    /// ```
2407    #[inline]
2408    fn from(octets: [u8; 16]) -> IpAddr {
2409        IpAddr::V6(Ipv6Addr::from(octets))
2410    }
2411}
2412
2413#[stable(feature = "ip_from_slice", since = "1.17.0")]
2414#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2415const impl From<[u16; 8]> for IpAddr {
2416    /// Creates an `IpAddr::V6` from an eight element 16-bit array.
2417    ///
2418    /// # Examples
2419    ///
2420    /// ```
2421    /// use std::net::{IpAddr, Ipv6Addr};
2422    ///
2423    /// let addr = IpAddr::from([
2424    ///     0x20du16, 0x20cu16, 0x20bu16, 0x20au16,
2425    ///     0x209u16, 0x208u16, 0x207u16, 0x206u16,
2426    /// ]);
2427    /// assert_eq!(
2428    ///     IpAddr::V6(Ipv6Addr::new(
2429    ///         0x20d, 0x20c, 0x20b, 0x20a,
2430    ///         0x209, 0x208, 0x207, 0x206,
2431    ///     )),
2432    ///     addr
2433    /// );
2434    /// ```
2435    #[inline]
2436    fn from(segments: [u16; 8]) -> IpAddr {
2437        IpAddr::V6(Ipv6Addr::from(segments))
2438    }
2439}
2440
2441#[stable(feature = "ip_bitops", since = "1.75.0")]
2442#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
2443const impl Not for Ipv4Addr {
2444    type Output = Ipv4Addr;
2445
2446    #[inline]
2447    fn not(mut self) -> Ipv4Addr {
2448        let mut idx = 0;
2449        while idx < 4 {
2450            self.octets[idx] = !self.octets[idx];
2451            idx += 1;
2452        }
2453        self
2454    }
2455}
2456
2457#[stable(feature = "ip_bitops", since = "1.75.0")]
2458#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
2459const impl Not for &'_ Ipv4Addr {
2460    type Output = Ipv4Addr;
2461
2462    #[inline]
2463    fn not(self) -> Ipv4Addr {
2464        !*self
2465    }
2466}
2467
2468#[stable(feature = "ip_bitops", since = "1.75.0")]
2469#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
2470const impl Not for Ipv6Addr {
2471    type Output = Ipv6Addr;
2472
2473    #[inline]
2474    fn not(mut self) -> Ipv6Addr {
2475        let mut idx = 0;
2476        while idx < 16 {
2477            self.octets[idx] = !self.octets[idx];
2478            idx += 1;
2479        }
2480        self
2481    }
2482}
2483
2484#[stable(feature = "ip_bitops", since = "1.75.0")]
2485#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
2486const impl Not for &'_ Ipv6Addr {
2487    type Output = Ipv6Addr;
2488
2489    #[inline]
2490    fn not(self) -> Ipv6Addr {
2491        !*self
2492    }
2493}
2494
2495macro_rules! bitop_impls {
2496    ($(
2497        $(#[$attr:meta])*
2498        impl ($BitOp:ident, $BitOpAssign:ident) for $ty:ty = ($bitop:ident, $bitop_assign:ident);
2499    )*) => {
2500        $(
2501            $(#[$attr])*
2502            const impl $BitOpAssign for $ty {
2503                fn $bitop_assign(&mut self, rhs: $ty) {
2504                    let mut idx = 0;
2505                    while idx < self.octets.len() {
2506                        self.octets[idx].$bitop_assign(rhs.octets[idx]);
2507                        idx += 1;
2508                    }
2509                }
2510            }
2511
2512            $(#[$attr])*
2513            const impl $BitOpAssign<&'_ $ty> for $ty {
2514                fn $bitop_assign(&mut self, rhs: &'_ $ty) {
2515                    self.$bitop_assign(*rhs);
2516                }
2517            }
2518
2519            $(#[$attr])*
2520            const impl $BitOp for $ty {
2521                type Output = $ty;
2522
2523                #[inline]
2524                fn $bitop(mut self, rhs: $ty) -> $ty {
2525                    self.$bitop_assign(rhs);
2526                    self
2527                }
2528            }
2529
2530            $(#[$attr])*
2531            const impl $BitOp<&'_ $ty> for $ty {
2532                type Output = $ty;
2533
2534                #[inline]
2535                fn $bitop(mut self, rhs: &'_ $ty) -> $ty {
2536                    self.$bitop_assign(*rhs);
2537                    self
2538                }
2539            }
2540
2541            $(#[$attr])*
2542            const impl $BitOp<$ty> for &'_ $ty {
2543                type Output = $ty;
2544
2545                #[inline]
2546                fn $bitop(self, rhs: $ty) -> $ty {
2547                    let mut lhs = *self;
2548                    lhs.$bitop_assign(rhs);
2549                    lhs
2550                }
2551            }
2552
2553            $(#[$attr])*
2554            const impl $BitOp<&'_ $ty> for &'_ $ty {
2555                type Output = $ty;
2556
2557                #[inline]
2558                fn $bitop(self, rhs: &'_ $ty) -> $ty {
2559                    let mut lhs = *self;
2560                    lhs.$bitop_assign(*rhs);
2561                    lhs
2562                }
2563            }
2564        )*
2565    };
2566}
2567
2568bitop_impls! {
2569    #[stable(feature = "ip_bitops", since = "1.75.0")]
2570    #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
2571    impl (BitAnd, BitAndAssign) for Ipv4Addr = (bitand, bitand_assign);
2572    #[stable(feature = "ip_bitops", since = "1.75.0")]
2573    #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
2574    impl (BitOr, BitOrAssign) for Ipv4Addr = (bitor, bitor_assign);
2575
2576    #[stable(feature = "ip_bitops", since = "1.75.0")]
2577    #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
2578    impl (BitAnd, BitAndAssign) for Ipv6Addr = (bitand, bitand_assign);
2579    #[stable(feature = "ip_bitops", since = "1.75.0")]
2580    #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
2581    impl (BitOr, BitOrAssign) for Ipv6Addr = (bitor, bitor_assign);
2582}