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