Skip to main content

core/net/
ip_addr.rs

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