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