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