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