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