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