]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/ip.rs
pin docs: add some forward references
[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 use crate::cmp::Ordering;
10 use crate::fmt::{self, Write as FmtWrite};
11 use crate::hash;
12 use crate::io::Write as IoWrite;
13 use crate::mem::transmute;
14 use crate::sys::net::netc as c;
15 use crate::sys_common::{AsInner, FromInner};
16
17 /// An IP address, either IPv4 or IPv6.
18 ///
19 /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
20 /// respective documentation for more details.
21 ///
22 /// The size of an `IpAddr` instance may vary depending on the target operating
23 /// system.
24 ///
25 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
26 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
27 ///
28 /// # Examples
29 ///
30 /// ```
31 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
32 ///
33 /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
34 /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
35 ///
36 /// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
37 /// assert_eq!("::1".parse(), Ok(localhost_v6));
38 ///
39 /// assert_eq!(localhost_v4.is_ipv6(), false);
40 /// assert_eq!(localhost_v4.is_ipv4(), true);
41 /// ```
42 #[stable(feature = "ip_addr", since = "1.7.0")]
43 #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
44 pub enum IpAddr {
45     /// An IPv4 address.
46     #[stable(feature = "ip_addr", since = "1.7.0")]
47     V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
48     /// An IPv6 address.
49     #[stable(feature = "ip_addr", since = "1.7.0")]
50     V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
51 }
52
53 /// An IPv4 address.
54 ///
55 /// IPv4 addresses are defined as 32-bit integers in [IETF RFC 791].
56 /// They are usually represented as four octets.
57 ///
58 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
59 ///
60 /// The size of an `Ipv4Addr` struct may vary depending on the target operating
61 /// system.
62 ///
63 /// [IETF RFC 791]: https://tools.ietf.org/html/rfc791
64 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
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`]: ../../std/str/trait.FromStr.html
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 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
100 ///
101 /// # Textual representation
102 ///
103 /// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
104 /// an IPv6 address in text, but in general, each segments is written in hexadecimal
105 /// notation, and segments are separated by `:`. For more information, see
106 /// [IETF RFC 5952].
107 ///
108 /// [`FromStr`]: ../../std/str/trait.FromStr.html
109 /// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
110 ///
111 /// # Examples
112 ///
113 /// ```
114 /// use std::net::Ipv6Addr;
115 ///
116 /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
117 /// assert_eq!("::1".parse(), Ok(localhost));
118 /// assert_eq!(localhost.is_loopback(), true);
119 /// ```
120 #[derive(Copy)]
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub struct Ipv6Addr {
123     inner: c::in6_addr,
124 }
125
126 #[allow(missing_docs)]
127 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
128 pub enum Ipv6MulticastScope {
129     InterfaceLocal,
130     LinkLocal,
131     RealmLocal,
132     AdminLocal,
133     SiteLocal,
134     OrganizationLocal,
135     Global,
136 }
137
138 impl IpAddr {
139     /// Returns [`true`] for the special 'unspecified' address.
140     ///
141     /// See the documentation for [`Ipv4Addr::is_unspecified`][IPv4] and
142     /// [`Ipv6Addr::is_unspecified`][IPv6] for more details.
143     ///
144     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_unspecified
145     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_unspecified
146     /// [`true`]: ../../std/primitive.bool.html
147     ///
148     /// # Examples
149     ///
150     /// ```
151     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
152     ///
153     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
154     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
155     /// ```
156     #[stable(feature = "ip_shared", since = "1.12.0")]
157     pub fn is_unspecified(&self) -> bool {
158         match self {
159             IpAddr::V4(ip) => ip.is_unspecified(),
160             IpAddr::V6(ip) => ip.is_unspecified(),
161         }
162     }
163
164     /// Returns [`true`] if this is a loopback address.
165     ///
166     /// See the documentation for [`Ipv4Addr::is_loopback`][IPv4] and
167     /// [`Ipv6Addr::is_loopback`][IPv6] for more details.
168     ///
169     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_loopback
170     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_loopback
171     /// [`true`]: ../../std/primitive.bool.html
172     ///
173     /// # Examples
174     ///
175     /// ```
176     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
177     ///
178     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
179     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
180     /// ```
181     #[stable(feature = "ip_shared", since = "1.12.0")]
182     pub fn is_loopback(&self) -> bool {
183         match self {
184             IpAddr::V4(ip) => ip.is_loopback(),
185             IpAddr::V6(ip) => ip.is_loopback(),
186         }
187     }
188
189     /// Returns [`true`] if the address appears to be globally routable.
190     ///
191     /// See the documentation for [`Ipv4Addr::is_global`][IPv4] and
192     /// [`Ipv6Addr::is_global`][IPv6] for more details.
193     ///
194     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_global
195     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_global
196     /// [`true`]: ../../std/primitive.bool.html
197     ///
198     /// # Examples
199     ///
200     /// ```
201     /// #![feature(ip)]
202     ///
203     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
204     ///
205     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
206     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
207     /// ```
208     pub fn is_global(&self) -> bool {
209         match self {
210             IpAddr::V4(ip) => ip.is_global(),
211             IpAddr::V6(ip) => ip.is_global(),
212         }
213     }
214
215     /// Returns [`true`] if this is a multicast address.
216     ///
217     /// See the documentation for [`Ipv4Addr::is_multicast`][IPv4] and
218     /// [`Ipv6Addr::is_multicast`][IPv6] for more details.
219     ///
220     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_multicast
221     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_multicast
222     /// [`true`]: ../../std/primitive.bool.html
223     ///
224     /// # Examples
225     ///
226     /// ```
227     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
228     ///
229     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
230     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
231     /// ```
232     #[stable(feature = "ip_shared", since = "1.12.0")]
233     pub fn is_multicast(&self) -> bool {
234         match self {
235             IpAddr::V4(ip) => ip.is_multicast(),
236             IpAddr::V6(ip) => ip.is_multicast(),
237         }
238     }
239
240     /// Returns [`true`] if this address is in a range designated for documentation.
241     ///
242     /// See the documentation for [`Ipv4Addr::is_documentation`][IPv4] and
243     /// [`Ipv6Addr::is_documentation`][IPv6] for more details.
244     ///
245     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_documentation
246     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_documentation
247     /// [`true`]: ../../std/primitive.bool.html
248     ///
249     /// # Examples
250     ///
251     /// ```
252     /// #![feature(ip)]
253     ///
254     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
255     ///
256     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
257     /// assert_eq!(
258     ///     IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
259     ///     true
260     /// );
261     /// ```
262     pub fn is_documentation(&self) -> bool {
263         match self {
264             IpAddr::V4(ip) => ip.is_documentation(),
265             IpAddr::V6(ip) => ip.is_documentation(),
266         }
267     }
268
269     /// Returns [`true`] if this address is an [IPv4 address], and [`false`] otherwise.
270     ///
271     /// [`true`]: ../../std/primitive.bool.html
272     /// [`false`]: ../../std/primitive.bool.html
273     /// [IPv4 address]: #variant.V4
274     ///
275     /// # Examples
276     ///
277     /// ```
278     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
279     ///
280     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
281     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
282     /// ```
283     #[stable(feature = "ipaddr_checker", since = "1.16.0")]
284     pub fn is_ipv4(&self) -> bool {
285         matches!(self, IpAddr::V4(_))
286     }
287
288     /// Returns [`true`] if this address is an [IPv6 address], and [`false`] otherwise.
289     ///
290     /// [`true`]: ../../std/primitive.bool.html
291     /// [`false`]: ../../std/primitive.bool.html
292     /// [IPv6 address]: #variant.V6
293     ///
294     /// # Examples
295     ///
296     /// ```
297     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
298     ///
299     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
300     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
301     /// ```
302     #[stable(feature = "ipaddr_checker", since = "1.16.0")]
303     pub fn is_ipv6(&self) -> bool {
304         matches!(self, IpAddr::V6(_))
305     }
306 }
307
308 impl Ipv4Addr {
309     /// Creates a new IPv4 address from four eight-bit octets.
310     ///
311     /// The result will represent the IP address `a`.`b`.`c`.`d`.
312     ///
313     /// # Examples
314     ///
315     /// ```
316     /// use std::net::Ipv4Addr;
317     ///
318     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
319     /// ```
320     #[stable(feature = "rust1", since = "1.0.0")]
321     #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
322     pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
323         // `s_addr` is stored as BE on all machine and the array is in BE order.
324         // So the native endian conversion method is used so that it's never swapped.
325         Ipv4Addr { inner: c::in_addr { s_addr: u32::from_ne_bytes([a, b, c, d]) } }
326     }
327
328     /// An IPv4 address with the address pointing to localhost: 127.0.0.1.
329     ///
330     /// # Examples
331     ///
332     /// ```
333     /// use std::net::Ipv4Addr;
334     ///
335     /// let addr = Ipv4Addr::LOCALHOST;
336     /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
337     /// ```
338     #[stable(feature = "ip_constructors", since = "1.30.0")]
339     pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
340
341     /// An IPv4 address representing an unspecified address: 0.0.0.0
342     ///
343     /// # Examples
344     ///
345     /// ```
346     /// use std::net::Ipv4Addr;
347     ///
348     /// let addr = Ipv4Addr::UNSPECIFIED;
349     /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
350     /// ```
351     #[stable(feature = "ip_constructors", since = "1.30.0")]
352     pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
353
354     /// An IPv4 address representing the broadcast address: 255.255.255.255
355     ///
356     /// # Examples
357     ///
358     /// ```
359     /// use std::net::Ipv4Addr;
360     ///
361     /// let addr = Ipv4Addr::BROADCAST;
362     /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
363     /// ```
364     #[stable(feature = "ip_constructors", since = "1.30.0")]
365     pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
366
367     /// Returns the four eight-bit integers that make up this address.
368     ///
369     /// # Examples
370     ///
371     /// ```
372     /// use std::net::Ipv4Addr;
373     ///
374     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
375     /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
376     /// ```
377     #[stable(feature = "rust1", since = "1.0.0")]
378     pub fn octets(&self) -> [u8; 4] {
379         // This returns the order we want because s_addr is stored in big-endian.
380         self.inner.s_addr.to_ne_bytes()
381     }
382
383     /// Returns [`true`] for the special 'unspecified' address (0.0.0.0).
384     ///
385     /// This property is defined in _UNIX Network Programming, Second Edition_,
386     /// W. Richard Stevens, p. 891; see also [ip7].
387     ///
388     /// [ip7]: http://man7.org/linux/man-pages/man7/ip.7.html
389     /// [`true`]: ../../std/primitive.bool.html
390     ///
391     /// # Examples
392     ///
393     /// ```
394     /// use std::net::Ipv4Addr;
395     ///
396     /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
397     /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
398     /// ```
399     #[stable(feature = "ip_shared", since = "1.12.0")]
400     #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
401     pub const fn is_unspecified(&self) -> bool {
402         self.inner.s_addr == 0
403     }
404
405     /// Returns [`true`] if this is a loopback address (127.0.0.0/8).
406     ///
407     /// This property is defined by [IETF RFC 1122].
408     ///
409     /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
410     /// [`true`]: ../../std/primitive.bool.html
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// use std::net::Ipv4Addr;
416     ///
417     /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
418     /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
419     /// ```
420     #[stable(since = "1.7.0", feature = "ip_17")]
421     pub fn is_loopback(&self) -> bool {
422         self.octets()[0] == 127
423     }
424
425     /// Returns [`true`] if this is a private address.
426     ///
427     /// The private address ranges are defined in [IETF RFC 1918] and include:
428     ///
429     ///  - 10.0.0.0/8
430     ///  - 172.16.0.0/12
431     ///  - 192.168.0.0/16
432     ///
433     /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
434     /// [`true`]: ../../std/primitive.bool.html
435     ///
436     /// # Examples
437     ///
438     /// ```
439     /// use std::net::Ipv4Addr;
440     ///
441     /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
442     /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
443     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
444     /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
445     /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
446     /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
447     /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
448     /// ```
449     #[stable(since = "1.7.0", feature = "ip_17")]
450     pub fn is_private(&self) -> bool {
451         match self.octets() {
452             [10, ..] => true,
453             [172, b, ..] if b >= 16 && b <= 31 => true,
454             [192, 168, ..] => true,
455             _ => false,
456         }
457     }
458
459     /// Returns [`true`] if the address is link-local (169.254.0.0/16).
460     ///
461     /// This property is defined by [IETF RFC 3927].
462     ///
463     /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
464     /// [`true`]: ../../std/primitive.bool.html
465     ///
466     /// # Examples
467     ///
468     /// ```
469     /// use std::net::Ipv4Addr;
470     ///
471     /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
472     /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
473     /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
474     /// ```
475     #[stable(since = "1.7.0", feature = "ip_17")]
476     pub fn is_link_local(&self) -> bool {
477         match self.octets() {
478             [169, 254, ..] => true,
479             _ => false,
480         }
481     }
482
483     /// Returns [`true`] if the address appears to be globally routable.
484     /// See [iana-ipv4-special-registry][ipv4-sr].
485     ///
486     /// The following return false:
487     ///
488     /// - private addresses (see [`is_private()`](#method.is_private))
489     /// - the loopback address (see [`is_loopback()`](#method.is_loopback))
490     /// - the link-local address (see [`is_link_local()`](#method.is_link_local))
491     /// - the broadcast address (see [`is_broadcast()`](#method.is_broadcast))
492     /// - addresses used for documentation (see [`is_documentation()`](#method.is_documentation))
493     /// - the unspecified address (see [`is_unspecified()`](#method.is_unspecified)), and the whole
494     ///   0.0.0.0/8 block
495     /// - addresses reserved for future protocols (see
496     /// [`is_ietf_protocol_assignment()`](#method.is_ietf_protocol_assignment), except
497     /// `192.0.0.9/32` and `192.0.0.10/32` which are globally routable
498     /// - addresses reserved for future use (see [`is_reserved()`](#method.is_reserved)
499     /// - addresses reserved for networking devices benchmarking (see
500     /// [`is_benchmarking`](#method.is_benchmarking))
501     ///
502     /// [ipv4-sr]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
503     /// [`true`]: ../../std/primitive.bool.html
504     ///
505     /// # Examples
506     ///
507     /// ```
508     /// #![feature(ip)]
509     ///
510     /// use std::net::Ipv4Addr;
511     ///
512     /// // private addresses are not global
513     /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
514     /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
515     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
516     ///
517     /// // the 0.0.0.0/8 block is not global
518     /// assert_eq!(Ipv4Addr::new(0, 1, 2, 3).is_global(), false);
519     /// // in particular, the unspecified address is not global
520     /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_global(), false);
521     ///
522     /// // the loopback address is not global
523     /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_global(), false);
524     ///
525     /// // link local addresses are not global
526     /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
527     ///
528     /// // the broadcast address is not global
529     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_global(), false);
530     ///
531     /// // the address space designated for documentation is not global
532     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
533     /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
534     /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
535     ///
536     /// // shared addresses are not global
537     /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
538     ///
539     /// // addresses reserved for protocol assignment are not global
540     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_global(), false);
541     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_global(), false);
542     ///
543     /// // addresses reserved for future use are not global
544     /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
545     ///
546     /// // addresses reserved for network devices benchmarking are not global
547     /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
548     ///
549     /// // All the other addresses are global
550     /// assert_eq!(Ipv4Addr::new(1, 1, 1, 1).is_global(), true);
551     /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
552     /// ```
553     pub fn is_global(&self) -> bool {
554         // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two
555         // globally routable addresses in the 192.0.0.0/24 range.
556         if u32::from(*self) == 0xc0000009 || u32::from(*self) == 0xc000000a {
557             return true;
558         }
559         !self.is_private()
560             && !self.is_loopback()
561             && !self.is_link_local()
562             && !self.is_broadcast()
563             && !self.is_documentation()
564             && !self.is_shared()
565             && !self.is_ietf_protocol_assignment()
566             && !self.is_reserved()
567             && !self.is_benchmarking()
568             // Make sure the address is not in 0.0.0.0/8
569             && self.octets()[0] != 0
570     }
571
572     /// Returns [`true`] if this address is part of the Shared Address Space defined in
573     /// [IETF RFC 6598] (`100.64.0.0/10`).
574     ///
575     /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
576     /// [`true`]: ../../std/primitive.bool.html
577     ///
578     /// # Examples
579     ///
580     /// ```
581     /// #![feature(ip)]
582     /// use std::net::Ipv4Addr;
583     ///
584     /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
585     /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
586     /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
587     /// ```
588     pub 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     /// [`true`]: ../../std/primitive.bool.html
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// #![feature(ip)]
611     /// use std::net::Ipv4Addr;
612     ///
613     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_ietf_protocol_assignment(), true);
614     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 8).is_ietf_protocol_assignment(), true);
615     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 9).is_ietf_protocol_assignment(), true);
616     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_ietf_protocol_assignment(), true);
617     /// assert_eq!(Ipv4Addr::new(192, 0, 1, 0).is_ietf_protocol_assignment(), false);
618     /// assert_eq!(Ipv4Addr::new(191, 255, 255, 255).is_ietf_protocol_assignment(), false);
619     /// ```
620     pub fn is_ietf_protocol_assignment(&self) -> bool {
621         self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0
622     }
623
624     /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
625     /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
626     /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
627     ///
628     /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
629     /// [errata 423]: https://www.rfc-editor.org/errata/eid423
630     /// [`true`]: ../../std/primitive.bool.html
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     pub fn is_benchmarking(&self) -> bool {
644         self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
645     }
646
647     /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
648     /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
649     /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
650     /// it is obviously not reserved for future use.
651     ///
652     /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
653     /// [`true`]: ../../std/primitive.bool.html
654     ///
655     /// # Warning
656     ///
657     /// As IANA assigns new addresses, this method will be
658     /// updated. This may result in non-reserved addresses being
659     /// treated as reserved in code that relies on an outdated version
660     /// of this method.
661     ///
662     /// # Examples
663     ///
664     /// ```
665     /// #![feature(ip)]
666     /// use std::net::Ipv4Addr;
667     ///
668     /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
669     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
670     ///
671     /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
672     /// // The broadcast address is not considered as reserved for future use by this implementation
673     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
674     /// ```
675     pub fn is_reserved(&self) -> bool {
676         self.octets()[0] & 240 == 240 && !self.is_broadcast()
677     }
678
679     /// Returns [`true`] if this is a multicast address (224.0.0.0/4).
680     ///
681     /// Multicast addresses have a most significant octet between 224 and 239,
682     /// and is defined by [IETF RFC 5771].
683     ///
684     /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
685     /// [`true`]: ../../std/primitive.bool.html
686     ///
687     /// # Examples
688     ///
689     /// ```
690     /// use std::net::Ipv4Addr;
691     ///
692     /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
693     /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
694     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
695     /// ```
696     #[stable(since = "1.7.0", feature = "ip_17")]
697     pub fn is_multicast(&self) -> bool {
698         self.octets()[0] >= 224 && self.octets()[0] <= 239
699     }
700
701     /// Returns [`true`] if this is a broadcast address (255.255.255.255).
702     ///
703     /// A broadcast address has all octets set to 255 as defined in [IETF RFC 919].
704     ///
705     /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
706     /// [`true`]: ../../std/primitive.bool.html
707     ///
708     /// # Examples
709     ///
710     /// ```
711     /// use std::net::Ipv4Addr;
712     ///
713     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
714     /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
715     /// ```
716     #[stable(since = "1.7.0", feature = "ip_17")]
717     pub fn is_broadcast(&self) -> bool {
718         self == &Self::BROADCAST
719     }
720
721     /// Returns [`true`] if this address is in a range designated for documentation.
722     ///
723     /// This is defined in [IETF RFC 5737]:
724     ///
725     /// - 192.0.2.0/24 (TEST-NET-1)
726     /// - 198.51.100.0/24 (TEST-NET-2)
727     /// - 203.0.113.0/24 (TEST-NET-3)
728     ///
729     /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
730     /// [`true`]: ../../std/primitive.bool.html
731     ///
732     /// # Examples
733     ///
734     /// ```
735     /// use std::net::Ipv4Addr;
736     ///
737     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
738     /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
739     /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
740     /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
741     /// ```
742     #[stable(since = "1.7.0", feature = "ip_17")]
743     pub fn is_documentation(&self) -> bool {
744         match self.octets() {
745             [192, 0, 2, _] => true,
746             [198, 51, 100, _] => true,
747             [203, 0, 113, _] => true,
748             _ => false,
749         }
750     }
751
752     /// Converts this address to an IPv4-compatible [IPv6 address].
753     ///
754     /// a.b.c.d becomes ::a.b.c.d
755     ///
756     /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
757     ///
758     /// # Examples
759     ///
760     /// ```
761     /// use std::net::{Ipv4Addr, Ipv6Addr};
762     ///
763     /// assert_eq!(
764     ///     Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
765     ///     Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 767)
766     /// );
767     /// ```
768     #[stable(feature = "rust1", since = "1.0.0")]
769     pub fn to_ipv6_compatible(&self) -> Ipv6Addr {
770         let [a, b, c, d] = self.octets();
771         Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d])
772     }
773
774     /// Converts this address to an IPv4-mapped [IPv6 address].
775     ///
776     /// a.b.c.d becomes ::ffff:a.b.c.d
777     ///
778     /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
779     ///
780     /// # Examples
781     ///
782     /// ```
783     /// use std::net::{Ipv4Addr, Ipv6Addr};
784     ///
785     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
786     ///            Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 49152, 767));
787     /// ```
788     #[stable(feature = "rust1", since = "1.0.0")]
789     pub fn to_ipv6_mapped(&self) -> Ipv6Addr {
790         let [a, b, c, d] = self.octets();
791         Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d])
792     }
793 }
794
795 #[stable(feature = "ip_addr", since = "1.7.0")]
796 impl fmt::Display for IpAddr {
797     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
798         match self {
799             IpAddr::V4(ip) => ip.fmt(fmt),
800             IpAddr::V6(ip) => ip.fmt(fmt),
801         }
802     }
803 }
804
805 #[stable(feature = "ip_from_ip", since = "1.16.0")]
806 impl From<Ipv4Addr> for IpAddr {
807     /// Copies this address to a new `IpAddr::V4`.
808     ///
809     /// # Examples
810     ///
811     /// ```
812     /// use std::net::{IpAddr, Ipv4Addr};
813     ///
814     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
815     ///
816     /// assert_eq!(
817     ///     IpAddr::V4(addr),
818     ///     IpAddr::from(addr)
819     /// )
820     /// ```
821     fn from(ipv4: Ipv4Addr) -> IpAddr {
822         IpAddr::V4(ipv4)
823     }
824 }
825
826 #[stable(feature = "ip_from_ip", since = "1.16.0")]
827 impl From<Ipv6Addr> for IpAddr {
828     /// Copies this address to a new `IpAddr::V6`.
829     ///
830     /// # Examples
831     ///
832     /// ```
833     /// use std::net::{IpAddr, Ipv6Addr};
834     ///
835     /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
836     ///
837     /// assert_eq!(
838     ///     IpAddr::V6(addr),
839     ///     IpAddr::from(addr)
840     /// );
841     /// ```
842     fn from(ipv6: Ipv6Addr) -> IpAddr {
843         IpAddr::V6(ipv6)
844     }
845 }
846
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl fmt::Display for Ipv4Addr {
849     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
850         let octets = self.octets();
851         // Fast Path: if there's no alignment stuff, write directly to the buffer
852         if fmt.precision().is_none() && fmt.width().is_none() {
853             write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
854         } else {
855             const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
856             let mut buf = [0u8; IPV4_BUF_LEN];
857             let mut buf_slice = &mut buf[..];
858
859             // Note: The call to write should never fail, hence the unwrap
860             write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
861             let len = IPV4_BUF_LEN - buf_slice.len();
862
863             // This unsafe is OK because we know what is being written to the buffer
864             let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
865             fmt.pad(buf)
866         }
867     }
868 }
869
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl fmt::Debug for Ipv4Addr {
872     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
873         fmt::Display::fmt(self, fmt)
874     }
875 }
876
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl Clone for Ipv4Addr {
879     fn clone(&self) -> Ipv4Addr {
880         *self
881     }
882 }
883
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl PartialEq for Ipv4Addr {
886     fn eq(&self, other: &Ipv4Addr) -> bool {
887         self.inner.s_addr == other.inner.s_addr
888     }
889 }
890
891 #[stable(feature = "ip_cmp", since = "1.16.0")]
892 impl PartialEq<Ipv4Addr> for IpAddr {
893     fn eq(&self, other: &Ipv4Addr) -> bool {
894         match self {
895             IpAddr::V4(v4) => v4 == other,
896             IpAddr::V6(_) => false,
897         }
898     }
899 }
900
901 #[stable(feature = "ip_cmp", since = "1.16.0")]
902 impl PartialEq<IpAddr> for Ipv4Addr {
903     fn eq(&self, other: &IpAddr) -> bool {
904         match other {
905             IpAddr::V4(v4) => self == v4,
906             IpAddr::V6(_) => false,
907         }
908     }
909 }
910
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl Eq for Ipv4Addr {}
913
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl hash::Hash for Ipv4Addr {
916     fn hash<H: hash::Hasher>(&self, s: &mut H) {
917         // `inner` is #[repr(packed)], so we need to copy `s_addr`.
918         { self.inner.s_addr }.hash(s)
919     }
920 }
921
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl PartialOrd for Ipv4Addr {
924     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
925         Some(self.cmp(other))
926     }
927 }
928
929 #[stable(feature = "ip_cmp", since = "1.16.0")]
930 impl PartialOrd<Ipv4Addr> for IpAddr {
931     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
932         match self {
933             IpAddr::V4(v4) => v4.partial_cmp(other),
934             IpAddr::V6(_) => Some(Ordering::Greater),
935         }
936     }
937 }
938
939 #[stable(feature = "ip_cmp", since = "1.16.0")]
940 impl PartialOrd<IpAddr> for Ipv4Addr {
941     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
942         match other {
943             IpAddr::V4(v4) => self.partial_cmp(v4),
944             IpAddr::V6(_) => Some(Ordering::Less),
945         }
946     }
947 }
948
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl Ord for Ipv4Addr {
951     fn cmp(&self, other: &Ipv4Addr) -> Ordering {
952         u32::from_be(self.inner.s_addr).cmp(&u32::from_be(other.inner.s_addr))
953     }
954 }
955
956 impl AsInner<c::in_addr> for Ipv4Addr {
957     fn as_inner(&self) -> &c::in_addr {
958         &self.inner
959     }
960 }
961
962 #[stable(feature = "ip_u32", since = "1.1.0")]
963 impl From<Ipv4Addr> for u32 {
964     /// Converts an `Ipv4Addr` into a host byte order `u32`.
965     ///
966     /// # Examples
967     ///
968     /// ```
969     /// use std::net::Ipv4Addr;
970     ///
971     /// let addr = Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe);
972     /// assert_eq!(0xcafebabe, u32::from(addr));
973     /// ```
974     fn from(ip: Ipv4Addr) -> u32 {
975         let ip = ip.octets();
976         u32::from_be_bytes(ip)
977     }
978 }
979
980 #[stable(feature = "ip_u32", since = "1.1.0")]
981 impl From<u32> for Ipv4Addr {
982     /// Converts a host byte order `u32` into an `Ipv4Addr`.
983     ///
984     /// # Examples
985     ///
986     /// ```
987     /// use std::net::Ipv4Addr;
988     ///
989     /// let addr = Ipv4Addr::from(0xcafebabe);
990     /// assert_eq!(Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe), addr);
991     /// ```
992     fn from(ip: u32) -> Ipv4Addr {
993         Ipv4Addr::from(ip.to_be_bytes())
994     }
995 }
996
997 #[stable(feature = "from_slice_v4", since = "1.9.0")]
998 impl From<[u8; 4]> for Ipv4Addr {
999     /// Creates an `Ipv4Addr` from a four element byte array.
1000     ///
1001     /// # Examples
1002     ///
1003     /// ```
1004     /// use std::net::Ipv4Addr;
1005     ///
1006     /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1007     /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1008     /// ```
1009     fn from(octets: [u8; 4]) -> Ipv4Addr {
1010         Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
1011     }
1012 }
1013
1014 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1015 impl From<[u8; 4]> for IpAddr {
1016     /// Creates an `IpAddr::V4` from a four element byte array.
1017     ///
1018     /// # Examples
1019     ///
1020     /// ```
1021     /// use std::net::{IpAddr, Ipv4Addr};
1022     ///
1023     /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1024     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1025     /// ```
1026     fn from(octets: [u8; 4]) -> IpAddr {
1027         IpAddr::V4(Ipv4Addr::from(octets))
1028     }
1029 }
1030
1031 impl Ipv6Addr {
1032     /// Creates a new IPv6 address from eight 16-bit segments.
1033     ///
1034     /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1035     ///
1036     /// # Examples
1037     ///
1038     /// ```
1039     /// use std::net::Ipv6Addr;
1040     ///
1041     /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1042     /// ```
1043     #[stable(feature = "rust1", since = "1.0.0")]
1044     #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1045     #[allow_internal_unstable(const_fn_transmute)]
1046     pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1047         let addr16 = [
1048             a.to_be(),
1049             b.to_be(),
1050             c.to_be(),
1051             d.to_be(),
1052             e.to_be(),
1053             f.to_be(),
1054             g.to_be(),
1055             h.to_be(),
1056         ];
1057         Ipv6Addr {
1058             inner: c::in6_addr {
1059                 // All elements in `addr16` are big endian.
1060                 // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1061                 s6_addr: unsafe { transmute::<_, [u8; 16]>(addr16) },
1062             },
1063         }
1064     }
1065
1066     /// An IPv6 address representing localhost: `::1`.
1067     ///
1068     /// # Examples
1069     ///
1070     /// ```
1071     /// use std::net::Ipv6Addr;
1072     ///
1073     /// let addr = Ipv6Addr::LOCALHOST;
1074     /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1075     /// ```
1076     #[stable(feature = "ip_constructors", since = "1.30.0")]
1077     pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1078
1079     /// An IPv6 address representing the unspecified address: `::`
1080     ///
1081     /// # Examples
1082     ///
1083     /// ```
1084     /// use std::net::Ipv6Addr;
1085     ///
1086     /// let addr = Ipv6Addr::UNSPECIFIED;
1087     /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1088     /// ```
1089     #[stable(feature = "ip_constructors", since = "1.30.0")]
1090     pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1091
1092     /// Returns the eight 16-bit segments that make up this address.
1093     ///
1094     /// # Examples
1095     ///
1096     /// ```
1097     /// use std::net::Ipv6Addr;
1098     ///
1099     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1100     ///            [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1101     /// ```
1102     #[stable(feature = "rust1", since = "1.0.0")]
1103     pub fn segments(&self) -> [u16; 8] {
1104         // All elements in `s6_addr` must be big endian.
1105         // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1106         let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.inner.s6_addr) };
1107         // We want native endian u16
1108         [
1109             u16::from_be(a),
1110             u16::from_be(b),
1111             u16::from_be(c),
1112             u16::from_be(d),
1113             u16::from_be(e),
1114             u16::from_be(f),
1115             u16::from_be(g),
1116             u16::from_be(h),
1117         ]
1118     }
1119
1120     /// Returns [`true`] for the special 'unspecified' address (::).
1121     ///
1122     /// This property is defined in [IETF RFC 4291].
1123     ///
1124     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1125     /// [`true`]: ../../std/primitive.bool.html
1126     ///
1127     /// # Examples
1128     ///
1129     /// ```
1130     /// use std::net::Ipv6Addr;
1131     ///
1132     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1133     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1134     /// ```
1135     #[stable(since = "1.7.0", feature = "ip_17")]
1136     pub fn is_unspecified(&self) -> bool {
1137         self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
1138     }
1139
1140     /// Returns [`true`] if this is a loopback address (::1).
1141     ///
1142     /// This property is defined in [IETF RFC 4291].
1143     ///
1144     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1145     /// [`true`]: ../../std/primitive.bool.html
1146     ///
1147     /// # Examples
1148     ///
1149     /// ```
1150     /// use std::net::Ipv6Addr;
1151     ///
1152     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1153     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1154     /// ```
1155     #[stable(since = "1.7.0", feature = "ip_17")]
1156     pub fn is_loopback(&self) -> bool {
1157         self.segments() == [0, 0, 0, 0, 0, 0, 0, 1]
1158     }
1159
1160     /// Returns [`true`] if the address appears to be globally routable.
1161     ///
1162     /// The following return [`false`]:
1163     ///
1164     /// - the loopback address
1165     /// - link-local and unique local unicast addresses
1166     /// - interface-, link-, realm-, admin- and site-local multicast addresses
1167     ///
1168     /// [`true`]: ../../std/primitive.bool.html
1169     /// [`false`]: ../../std/primitive.bool.html
1170     ///
1171     /// # Examples
1172     ///
1173     /// ```
1174     /// #![feature(ip)]
1175     ///
1176     /// use std::net::Ipv6Addr;
1177     ///
1178     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), true);
1179     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_global(), false);
1180     /// assert_eq!(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1).is_global(), true);
1181     /// ```
1182     pub fn is_global(&self) -> bool {
1183         match self.multicast_scope() {
1184             Some(Ipv6MulticastScope::Global) => true,
1185             None => self.is_unicast_global(),
1186             _ => false,
1187         }
1188     }
1189
1190     /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1191     ///
1192     /// This property is defined in [IETF RFC 4193].
1193     ///
1194     /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1195     /// [`true`]: ../../std/primitive.bool.html
1196     ///
1197     /// # Examples
1198     ///
1199     /// ```
1200     /// #![feature(ip)]
1201     ///
1202     /// use std::net::Ipv6Addr;
1203     ///
1204     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1205     /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1206     /// ```
1207     pub fn is_unique_local(&self) -> bool {
1208         (self.segments()[0] & 0xfe00) == 0xfc00
1209     }
1210
1211     /// Returns [`true`] if the address is a unicast link-local address (`fe80::/64`).
1212     ///
1213     /// A common mis-conception is to think that "unicast link-local addresses start with
1214     /// `fe80::`", but the [IETF RFC 4291] actually defines a stricter format for these addresses:
1215     ///
1216     /// ```no_rust
1217     /// |   10     |
1218     /// |  bits    |         54 bits         |          64 bits           |
1219     /// +----------+-------------------------+----------------------------+
1220     /// |1111111010|           0             |       interface ID         |
1221     /// +----------+-------------------------+----------------------------+
1222     /// ```
1223     ///
1224     /// This method validates the format defined in the RFC and won't recognize the following
1225     /// addresses such as `fe80:0:0:1::` or `fe81::` as unicast link-local addresses for example.
1226     /// If you need a less strict validation use [`is_unicast_link_local()`] instead.
1227     ///
1228     /// # Examples
1229     ///
1230     /// ```
1231     /// #![feature(ip)]
1232     ///
1233     /// use std::net::Ipv6Addr;
1234     ///
1235     /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0);
1236     /// assert!(ip.is_unicast_link_local_strict());
1237     ///
1238     /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff);
1239     /// assert!(ip.is_unicast_link_local_strict());
1240     ///
1241     /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0);
1242     /// assert!(!ip.is_unicast_link_local_strict());
1243     /// assert!(ip.is_unicast_link_local());
1244     ///
1245     /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0);
1246     /// assert!(!ip.is_unicast_link_local_strict());
1247     /// assert!(ip.is_unicast_link_local());
1248     /// ```
1249     ///
1250     /// # See also
1251     ///
1252     /// - [IETF RFC 4291 section 2.5.6]
1253     /// - [RFC 4291 errata 4406] (which has been rejected but provides useful
1254     ///   insight)
1255     /// - [`is_unicast_link_local()`]
1256     ///
1257     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1258     /// [IETF RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1259     /// [`true`]: ../../std/primitive.bool.html
1260     /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406
1261     /// [`is_unicast_link_local()`]: ../../std/net/struct.Ipv6Addr.html#method.is_unicast_link_local
1262     pub fn is_unicast_link_local_strict(&self) -> bool {
1263         (self.segments()[0] & 0xffff) == 0xfe80
1264             && (self.segments()[1] & 0xffff) == 0
1265             && (self.segments()[2] & 0xffff) == 0
1266             && (self.segments()[3] & 0xffff) == 0
1267     }
1268
1269     /// Returns [`true`] if the address is a unicast link-local address (`fe80::/10`).
1270     ///
1271     /// This method returns [`true`] for addresses in the range reserved by [RFC 4291 section 2.4],
1272     /// i.e. addresses with the following format:
1273     ///
1274     /// ```no_rust
1275     /// |   10     |
1276     /// |  bits    |         54 bits         |          64 bits           |
1277     /// +----------+-------------------------+----------------------------+
1278     /// |1111111010|    arbitratry value     |       interface ID         |
1279     /// +----------+-------------------------+----------------------------+
1280     /// ```
1281     ///
1282     /// As a result, this method consider addresses such as `fe80:0:0:1::` or `fe81::` to be
1283     /// unicast link-local addresses, whereas [`is_unicast_link_local_strict()`] does not. If you
1284     /// need a strict validation fully compliant with the RFC, use
1285     /// [`is_unicast_link_local_strict()`].
1286     ///
1287     /// # Examples
1288     ///
1289     /// ```
1290     /// #![feature(ip)]
1291     ///
1292     /// use std::net::Ipv6Addr;
1293     ///
1294     /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0);
1295     /// assert!(ip.is_unicast_link_local());
1296     ///
1297     /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff);
1298     /// assert!(ip.is_unicast_link_local());
1299     ///
1300     /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0);
1301     /// assert!(ip.is_unicast_link_local());
1302     /// assert!(!ip.is_unicast_link_local_strict());
1303     ///
1304     /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0);
1305     /// assert!(ip.is_unicast_link_local());
1306     /// assert!(!ip.is_unicast_link_local_strict());
1307     /// ```
1308     ///
1309     /// # See also
1310     ///
1311     /// - [IETF RFC 4291 section 2.4]
1312     /// - [RFC 4291 errata 4406] (which has been rejected but provides useful
1313     ///   insight)
1314     ///
1315     /// [IETF RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1316     /// [`true`]: ../../std/primitive.bool.html
1317     /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406
1318     /// [`is_unicast_link_local_strict()`]: ../../std/net/struct.Ipv6Addr.html#method.is_unicast_link_local_strict
1319     pub fn is_unicast_link_local(&self) -> bool {
1320         (self.segments()[0] & 0xffc0) == 0xfe80
1321     }
1322
1323     /// Returns [`true`] if this is a deprecated unicast site-local address (fec0::/10). The
1324     /// unicast site-local address format is defined in [RFC 4291 section 2.5.7] as:
1325     ///
1326     /// ```no_rust
1327     /// |   10     |
1328     /// |  bits    |         54 bits         |         64 bits            |
1329     /// +----------+-------------------------+----------------------------+
1330     /// |1111111011|        subnet ID        |       interface ID         |
1331     /// +----------+-------------------------+----------------------------+
1332     /// ```
1333     ///
1334     /// [`true`]: ../../std/primitive.bool.html
1335     /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1336     ///
1337     /// # Examples
1338     ///
1339     /// ```
1340     /// #![feature(ip)]
1341     ///
1342     /// use std::net::Ipv6Addr;
1343     ///
1344     /// assert_eq!(
1345     ///     Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_site_local(),
1346     ///     false
1347     /// );
1348     /// assert_eq!(Ipv6Addr::new(0xfec2, 0, 0, 0, 0, 0, 0, 0).is_unicast_site_local(), true);
1349     /// ```
1350     ///
1351     /// # Warning
1352     ///
1353     /// As per [RFC 3879], the whole `FEC0::/10` prefix is
1354     /// deprecated. New software must not support site-local
1355     /// addresses.
1356     ///
1357     /// [RFC 3879]: https://tools.ietf.org/html/rfc3879
1358     pub fn is_unicast_site_local(&self) -> bool {
1359         (self.segments()[0] & 0xffc0) == 0xfec0
1360     }
1361
1362     /// Returns [`true`] if this is an address reserved for documentation
1363     /// (2001:db8::/32).
1364     ///
1365     /// This property is defined in [IETF RFC 3849].
1366     ///
1367     /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1368     /// [`true`]: ../../std/primitive.bool.html
1369     ///
1370     /// # Examples
1371     ///
1372     /// ```
1373     /// #![feature(ip)]
1374     ///
1375     /// use std::net::Ipv6Addr;
1376     ///
1377     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1378     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1379     /// ```
1380     pub fn is_documentation(&self) -> bool {
1381         (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1382     }
1383
1384     /// Returns [`true`] if the address is a globally routable unicast address.
1385     ///
1386     /// The following return false:
1387     ///
1388     /// - the loopback address
1389     /// - the link-local addresses
1390     /// - unique local addresses
1391     /// - the unspecified address
1392     /// - the address range reserved for documentation
1393     ///
1394     /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1395     ///
1396     /// ```no_rust
1397     /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1398     /// be supported in new implementations (i.e., new implementations must treat this prefix as
1399     /// Global Unicast).
1400     /// ```
1401     ///
1402     /// [`true`]: ../../std/primitive.bool.html
1403     /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1404     ///
1405     /// # Examples
1406     ///
1407     /// ```
1408     /// #![feature(ip)]
1409     ///
1410     /// use std::net::Ipv6Addr;
1411     ///
1412     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1413     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1414     /// ```
1415     pub fn is_unicast_global(&self) -> bool {
1416         !self.is_multicast()
1417             && !self.is_loopback()
1418             && !self.is_unicast_link_local()
1419             && !self.is_unique_local()
1420             && !self.is_unspecified()
1421             && !self.is_documentation()
1422     }
1423
1424     /// Returns the address's multicast scope if the address is multicast.
1425     ///
1426     /// # Examples
1427     ///
1428     /// ```
1429     /// #![feature(ip)]
1430     ///
1431     /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1432     ///
1433     /// assert_eq!(
1434     ///     Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1435     ///     Some(Ipv6MulticastScope::Global)
1436     /// );
1437     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1438     /// ```
1439     pub fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1440         if self.is_multicast() {
1441             match self.segments()[0] & 0x000f {
1442                 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1443                 2 => Some(Ipv6MulticastScope::LinkLocal),
1444                 3 => Some(Ipv6MulticastScope::RealmLocal),
1445                 4 => Some(Ipv6MulticastScope::AdminLocal),
1446                 5 => Some(Ipv6MulticastScope::SiteLocal),
1447                 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1448                 14 => Some(Ipv6MulticastScope::Global),
1449                 _ => None,
1450             }
1451         } else {
1452             None
1453         }
1454     }
1455
1456     /// Returns [`true`] if this is a multicast address (ff00::/8).
1457     ///
1458     /// This property is defined by [IETF RFC 4291].
1459     ///
1460     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1461     /// [`true`]: ../../std/primitive.bool.html
1462     ///
1463     /// # Examples
1464     ///
1465     /// ```
1466     /// use std::net::Ipv6Addr;
1467     ///
1468     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1469     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1470     /// ```
1471     #[stable(since = "1.7.0", feature = "ip_17")]
1472     pub fn is_multicast(&self) -> bool {
1473         (self.segments()[0] & 0xff00) == 0xff00
1474     }
1475
1476     /// Converts this address to an [IPv4 address] if it's an "IPv4-mapped IPv6 address"
1477     /// defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1478     ///
1479     /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1480     /// All addresses *not* starting with `::ffff` will return `None`.
1481     ///
1482     /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
1483     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1484     /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1485     ///
1486     /// # Examples
1487     ///
1488     /// ```
1489     /// #![feature(ip)]
1490     ///
1491     /// use std::net::{Ipv4Addr, Ipv6Addr};
1492     ///
1493     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1494     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1495     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1496     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1497     /// ```
1498     pub fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1499         match self.octets() {
1500             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1501                 Some(Ipv4Addr::new(a, b, c, d))
1502             }
1503             _ => None,
1504         }
1505     }
1506
1507     /// Converts this address to an [IPv4 address]. Returns [`None`] if this address is
1508     /// neither IPv4-compatible or IPv4-mapped.
1509     ///
1510     /// ::a.b.c.d and ::ffff:a.b.c.d become a.b.c.d
1511     ///
1512     /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
1513     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1514     ///
1515     /// # Examples
1516     ///
1517     /// ```
1518     /// use std::net::{Ipv4Addr, Ipv6Addr};
1519     ///
1520     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1521     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1522     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1523     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1524     ///            Some(Ipv4Addr::new(0, 0, 0, 1)));
1525     /// ```
1526     #[stable(feature = "rust1", since = "1.0.0")]
1527     pub fn to_ipv4(&self) -> Option<Ipv4Addr> {
1528         if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1529             let [a, b] = ab.to_be_bytes();
1530             let [c, d] = cd.to_be_bytes();
1531             Some(Ipv4Addr::new(a, b, c, d))
1532         } else {
1533             None
1534         }
1535     }
1536
1537     /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1538     ///
1539     /// ```
1540     /// use std::net::Ipv6Addr;
1541     ///
1542     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1543     ///            [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1544     /// ```
1545     #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1546     #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1547     pub const fn octets(&self) -> [u8; 16] {
1548         self.inner.s6_addr
1549     }
1550 }
1551
1552 /// Write an Ipv6Addr, conforming to the canonical style described by
1553 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl fmt::Display for Ipv6Addr {
1556     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1557         // If there are no alignment requirements, write out the IP address to
1558         // f. Otherwise, write it to a local buffer, then use f.pad.
1559         if f.precision().is_none() && f.width().is_none() {
1560             let segments = self.segments();
1561
1562             // Special case for :: and ::1; otherwise they get written with the
1563             // IPv4 formatter
1564             if self.is_unspecified() {
1565                 f.write_str("::")
1566             } else if self.is_loopback() {
1567                 f.write_str("::1")
1568             } else if let Some(ipv4) = self.to_ipv4() {
1569                 match segments[5] {
1570                     // IPv4 Compatible address
1571                     0 => write!(f, "::{}", ipv4),
1572                     // IPv4 Mapped address
1573                     0xffff => write!(f, "::ffff:{}", ipv4),
1574                     _ => unreachable!(),
1575                 }
1576             } else {
1577                 #[derive(Copy, Clone, Default)]
1578                 struct Span {
1579                     start: usize,
1580                     len: usize,
1581                 }
1582
1583                 // Find the inner 0 span
1584                 let zeroes = {
1585                     let mut longest = Span::default();
1586                     let mut current = Span::default();
1587
1588                     for (i, &segment) in segments.iter().enumerate() {
1589                         if segment == 0 {
1590                             if current.len == 0 {
1591                                 current.start = i;
1592                             }
1593
1594                             current.len += 1;
1595
1596                             if current.len > longest.len {
1597                                 longest = current;
1598                             }
1599                         } else {
1600                             current = Span::default();
1601                         }
1602                     }
1603
1604                     longest
1605                 };
1606
1607                 /// Write a colon-separated part of the address
1608                 #[inline]
1609                 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1610                     if let Some(first) = chunk.first() {
1611                         fmt::LowerHex::fmt(first, f)?;
1612                         for segment in &chunk[1..] {
1613                             f.write_char(':')?;
1614                             fmt::LowerHex::fmt(segment, f)?;
1615                         }
1616                     }
1617                     Ok(())
1618                 }
1619
1620                 if zeroes.len > 1 {
1621                     fmt_subslice(f, &segments[..zeroes.start])?;
1622                     f.write_str("::")?;
1623                     fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1624                 } else {
1625                     fmt_subslice(f, &segments)
1626                 }
1627             }
1628         } else {
1629             // Slow path: write the address to a local buffer, the use f.pad.
1630             // Defined recursively by using the fast path to write to the
1631             // buffer.
1632
1633             // This is the largest possible size of an IPv6 address
1634             const IPV6_BUF_LEN: usize = (4 * 8) + 7;
1635             let mut buf = [0u8; IPV6_BUF_LEN];
1636             let mut buf_slice = &mut buf[..];
1637
1638             // Note: This call to write should never fail, so unwrap is okay.
1639             write!(buf_slice, "{}", self).unwrap();
1640             let len = IPV6_BUF_LEN - buf_slice.len();
1641
1642             // This is safe because we know exactly what can be in this buffer
1643             let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1644             f.pad(buf)
1645         }
1646     }
1647 }
1648
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 impl fmt::Debug for Ipv6Addr {
1651     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1652         fmt::Display::fmt(self, fmt)
1653     }
1654 }
1655
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 impl Clone for Ipv6Addr {
1658     fn clone(&self) -> Ipv6Addr {
1659         *self
1660     }
1661 }
1662
1663 #[stable(feature = "rust1", since = "1.0.0")]
1664 impl PartialEq for Ipv6Addr {
1665     fn eq(&self, other: &Ipv6Addr) -> bool {
1666         self.inner.s6_addr == other.inner.s6_addr
1667     }
1668 }
1669
1670 #[stable(feature = "ip_cmp", since = "1.16.0")]
1671 impl PartialEq<IpAddr> for Ipv6Addr {
1672     fn eq(&self, other: &IpAddr) -> bool {
1673         match other {
1674             IpAddr::V4(_) => false,
1675             IpAddr::V6(v6) => self == v6,
1676         }
1677     }
1678 }
1679
1680 #[stable(feature = "ip_cmp", since = "1.16.0")]
1681 impl PartialEq<Ipv6Addr> for IpAddr {
1682     fn eq(&self, other: &Ipv6Addr) -> bool {
1683         match self {
1684             IpAddr::V4(_) => false,
1685             IpAddr::V6(v6) => v6 == other,
1686         }
1687     }
1688 }
1689
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 impl Eq for Ipv6Addr {}
1692
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 impl hash::Hash for Ipv6Addr {
1695     fn hash<H: hash::Hasher>(&self, s: &mut H) {
1696         self.inner.s6_addr.hash(s)
1697     }
1698 }
1699
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 impl PartialOrd for Ipv6Addr {
1702     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1703         Some(self.cmp(other))
1704     }
1705 }
1706
1707 #[stable(feature = "ip_cmp", since = "1.16.0")]
1708 impl PartialOrd<Ipv6Addr> for IpAddr {
1709     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1710         match self {
1711             IpAddr::V4(_) => Some(Ordering::Less),
1712             IpAddr::V6(v6) => v6.partial_cmp(other),
1713         }
1714     }
1715 }
1716
1717 #[stable(feature = "ip_cmp", since = "1.16.0")]
1718 impl PartialOrd<IpAddr> for Ipv6Addr {
1719     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1720         match other {
1721             IpAddr::V4(_) => Some(Ordering::Greater),
1722             IpAddr::V6(v6) => self.partial_cmp(v6),
1723         }
1724     }
1725 }
1726
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl Ord for Ipv6Addr {
1729     fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1730         self.segments().cmp(&other.segments())
1731     }
1732 }
1733
1734 impl AsInner<c::in6_addr> for Ipv6Addr {
1735     fn as_inner(&self) -> &c::in6_addr {
1736         &self.inner
1737     }
1738 }
1739 impl FromInner<c::in6_addr> for Ipv6Addr {
1740     fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1741         Ipv6Addr { inner: addr }
1742     }
1743 }
1744
1745 #[stable(feature = "i128", since = "1.26.0")]
1746 impl From<Ipv6Addr> for u128 {
1747     /// Convert an `Ipv6Addr` into a host byte order `u128`.
1748     ///
1749     /// # Examples
1750     ///
1751     /// ```
1752     /// use std::net::Ipv6Addr;
1753     ///
1754     /// let addr = Ipv6Addr::new(
1755     ///     0x1020, 0x3040, 0x5060, 0x7080,
1756     ///     0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1757     /// );
1758     /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1759     /// ```
1760     fn from(ip: Ipv6Addr) -> u128 {
1761         let ip = ip.octets();
1762         u128::from_be_bytes(ip)
1763     }
1764 }
1765 #[stable(feature = "i128", since = "1.26.0")]
1766 impl From<u128> for Ipv6Addr {
1767     /// Convert a host byte order `u128` into an `Ipv6Addr`.
1768     ///
1769     /// # Examples
1770     ///
1771     /// ```
1772     /// use std::net::Ipv6Addr;
1773     ///
1774     /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1775     /// assert_eq!(
1776     ///     Ipv6Addr::new(
1777     ///         0x1020, 0x3040, 0x5060, 0x7080,
1778     ///         0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1779     ///     ),
1780     ///     addr);
1781     /// ```
1782     fn from(ip: u128) -> Ipv6Addr {
1783         Ipv6Addr::from(ip.to_be_bytes())
1784     }
1785 }
1786
1787 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1788 impl From<[u8; 16]> for Ipv6Addr {
1789     /// Creates an `Ipv6Addr` from a sixteen element byte array.
1790     ///
1791     /// # Examples
1792     ///
1793     /// ```
1794     /// use std::net::Ipv6Addr;
1795     ///
1796     /// let addr = Ipv6Addr::from([
1797     ///     25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1798     ///     17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1799     /// ]);
1800     /// assert_eq!(
1801     ///     Ipv6Addr::new(
1802     ///         0x1918, 0x1716,
1803     ///         0x1514, 0x1312,
1804     ///         0x1110, 0x0f0e,
1805     ///         0x0d0c, 0x0b0a
1806     ///     ),
1807     ///     addr
1808     /// );
1809     /// ```
1810     fn from(octets: [u8; 16]) -> Ipv6Addr {
1811         let inner = c::in6_addr { s6_addr: octets };
1812         Ipv6Addr::from_inner(inner)
1813     }
1814 }
1815
1816 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
1817 impl From<[u16; 8]> for Ipv6Addr {
1818     /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1819     ///
1820     /// # Examples
1821     ///
1822     /// ```
1823     /// use std::net::Ipv6Addr;
1824     ///
1825     /// let addr = Ipv6Addr::from([
1826     ///     525u16, 524u16, 523u16, 522u16,
1827     ///     521u16, 520u16, 519u16, 518u16,
1828     /// ]);
1829     /// assert_eq!(
1830     ///     Ipv6Addr::new(
1831     ///         0x20d, 0x20c,
1832     ///         0x20b, 0x20a,
1833     ///         0x209, 0x208,
1834     ///         0x207, 0x206
1835     ///     ),
1836     ///     addr
1837     /// );
1838     /// ```
1839     fn from(segments: [u16; 8]) -> Ipv6Addr {
1840         let [a, b, c, d, e, f, g, h] = segments;
1841         Ipv6Addr::new(a, b, c, d, e, f, g, h)
1842     }
1843 }
1844
1845 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1846 impl From<[u8; 16]> for IpAddr {
1847     /// Creates an `IpAddr::V6` from a sixteen element byte array.
1848     ///
1849     /// # Examples
1850     ///
1851     /// ```
1852     /// use std::net::{IpAddr, Ipv6Addr};
1853     ///
1854     /// let addr = IpAddr::from([
1855     ///     25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1856     ///     17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1857     /// ]);
1858     /// assert_eq!(
1859     ///     IpAddr::V6(Ipv6Addr::new(
1860     ///         0x1918, 0x1716,
1861     ///         0x1514, 0x1312,
1862     ///         0x1110, 0x0f0e,
1863     ///         0x0d0c, 0x0b0a
1864     ///     )),
1865     ///     addr
1866     /// );
1867     /// ```
1868     fn from(octets: [u8; 16]) -> IpAddr {
1869         IpAddr::V6(Ipv6Addr::from(octets))
1870     }
1871 }
1872
1873 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1874 impl From<[u16; 8]> for IpAddr {
1875     /// Creates an `IpAddr::V6` from an eight element 16-bit array.
1876     ///
1877     /// # Examples
1878     ///
1879     /// ```
1880     /// use std::net::{IpAddr, Ipv6Addr};
1881     ///
1882     /// let addr = IpAddr::from([
1883     ///     525u16, 524u16, 523u16, 522u16,
1884     ///     521u16, 520u16, 519u16, 518u16,
1885     /// ]);
1886     /// assert_eq!(
1887     ///     IpAddr::V6(Ipv6Addr::new(
1888     ///         0x20d, 0x20c,
1889     ///         0x20b, 0x20a,
1890     ///         0x209, 0x208,
1891     ///         0x207, 0x206
1892     ///     )),
1893     ///     addr
1894     /// );
1895     /// ```
1896     fn from(segments: [u16; 8]) -> IpAddr {
1897         IpAddr::V6(Ipv6Addr::from(segments))
1898     }
1899 }
1900
1901 // Tests for this module
1902 #[cfg(all(test, not(target_os = "emscripten")))]
1903 mod tests {
1904     use crate::net::test::{sa4, sa6, tsa};
1905     use crate::net::*;
1906     use crate::str::FromStr;
1907
1908     #[test]
1909     fn test_from_str_ipv4() {
1910         assert_eq!(Ok(Ipv4Addr::new(127, 0, 0, 1)), "127.0.0.1".parse());
1911         assert_eq!(Ok(Ipv4Addr::new(255, 255, 255, 255)), "255.255.255.255".parse());
1912         assert_eq!(Ok(Ipv4Addr::new(0, 0, 0, 0)), "0.0.0.0".parse());
1913
1914         // out of range
1915         let none: Option<Ipv4Addr> = "256.0.0.1".parse().ok();
1916         assert_eq!(None, none);
1917         // too short
1918         let none: Option<Ipv4Addr> = "255.0.0".parse().ok();
1919         assert_eq!(None, none);
1920         // too long
1921         let none: Option<Ipv4Addr> = "255.0.0.1.2".parse().ok();
1922         assert_eq!(None, none);
1923         // no number between dots
1924         let none: Option<Ipv4Addr> = "255.0..1".parse().ok();
1925         assert_eq!(None, none);
1926     }
1927
1928     #[test]
1929     fn test_from_str_ipv6() {
1930         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "0:0:0:0:0:0:0:0".parse());
1931         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "0:0:0:0:0:0:0:1".parse());
1932
1933         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "::1".parse());
1934         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "::".parse());
1935
1936         assert_eq!(
1937             Ok(Ipv6Addr::new(0x2a02, 0x6b8, 0, 0, 0, 0, 0x11, 0x11)),
1938             "2a02:6b8::11:11".parse()
1939         );
1940
1941         // too long group
1942         let none: Option<Ipv6Addr> = "::00000".parse().ok();
1943         assert_eq!(None, none);
1944         // too short
1945         let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7".parse().ok();
1946         assert_eq!(None, none);
1947         // too long
1948         let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7:8:9".parse().ok();
1949         assert_eq!(None, none);
1950         // triple colon
1951         let none: Option<Ipv6Addr> = "1:2:::6:7:8".parse().ok();
1952         assert_eq!(None, none);
1953         // two double colons
1954         let none: Option<Ipv6Addr> = "1:2::6::8".parse().ok();
1955         assert_eq!(None, none);
1956         // `::` indicating zero groups of zeros
1957         let none: Option<Ipv6Addr> = "1:2:3:4::5:6:7:8".parse().ok();
1958         assert_eq!(None, none);
1959     }
1960
1961     #[test]
1962     fn test_from_str_ipv4_in_ipv6() {
1963         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 545)), "::192.0.2.33".parse());
1964         assert_eq!(
1965             Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0xFFFF, 49152, 545)),
1966             "::FFFF:192.0.2.33".parse()
1967         );
1968         assert_eq!(
1969             Ok(Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 49152, 545)),
1970             "64:ff9b::192.0.2.33".parse()
1971         );
1972         assert_eq!(
1973             Ok(Ipv6Addr::new(0x2001, 0xdb8, 0x122, 0xc000, 0x2, 0x2100, 49152, 545)),
1974             "2001:db8:122:c000:2:2100:192.0.2.33".parse()
1975         );
1976
1977         // colon after v4
1978         let none: Option<Ipv4Addr> = "::127.0.0.1:".parse().ok();
1979         assert_eq!(None, none);
1980         // not enough groups
1981         let none: Option<Ipv6Addr> = "1.2.3.4.5:127.0.0.1".parse().ok();
1982         assert_eq!(None, none);
1983         // too many groups
1984         let none: Option<Ipv6Addr> = "1.2.3.4.5:6:7:127.0.0.1".parse().ok();
1985         assert_eq!(None, none);
1986     }
1987
1988     #[test]
1989     fn test_from_str_socket_addr() {
1990         assert_eq!(Ok(sa4(Ipv4Addr::new(77, 88, 21, 11), 80)), "77.88.21.11:80".parse());
1991         assert_eq!(
1992             Ok(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80)),
1993             "77.88.21.11:80".parse()
1994         );
1995         assert_eq!(
1996             Ok(sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53)),
1997             "[2a02:6b8:0:1::1]:53".parse()
1998         );
1999         assert_eq!(
2000             Ok(SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53, 0, 0)),
2001             "[2a02:6b8:0:1::1]:53".parse()
2002         );
2003         assert_eq!(
2004             Ok(sa6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7F00, 1), 22)),
2005             "[::127.0.0.1]:22".parse()
2006         );
2007         assert_eq!(
2008             Ok(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7F00, 1), 22, 0, 0)),
2009             "[::127.0.0.1]:22".parse()
2010         );
2011
2012         // without port
2013         let none: Option<SocketAddr> = "127.0.0.1".parse().ok();
2014         assert_eq!(None, none);
2015         // without port
2016         let none: Option<SocketAddr> = "127.0.0.1:".parse().ok();
2017         assert_eq!(None, none);
2018         // wrong brackets around v4
2019         let none: Option<SocketAddr> = "[127.0.0.1]:22".parse().ok();
2020         assert_eq!(None, none);
2021         // port out of range
2022         let none: Option<SocketAddr> = "127.0.0.1:123456".parse().ok();
2023         assert_eq!(None, none);
2024     }
2025
2026     #[test]
2027     fn ipv4_addr_to_string() {
2028         // Short address
2029         assert_eq!(Ipv4Addr::new(1, 1, 1, 1).to_string(), "1.1.1.1");
2030         // Long address
2031         assert_eq!(Ipv4Addr::new(127, 127, 127, 127).to_string(), "127.127.127.127");
2032
2033         // Test padding
2034         assert_eq!(&format!("{:16}", Ipv4Addr::new(1, 1, 1, 1)), "1.1.1.1         ");
2035         assert_eq!(&format!("{:>16}", Ipv4Addr::new(1, 1, 1, 1)), "         1.1.1.1");
2036     }
2037
2038     #[test]
2039     fn ipv6_addr_to_string() {
2040         // ipv4-mapped address
2041         let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280);
2042         assert_eq!(a1.to_string(), "::ffff:192.0.2.128");
2043
2044         // ipv4-compatible address
2045         let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x280);
2046         assert_eq!(a1.to_string(), "::192.0.2.128");
2047
2048         // v6 address with no zero segments
2049         assert_eq!(Ipv6Addr::new(8, 9, 10, 11, 12, 13, 14, 15).to_string(), "8:9:a:b:c:d:e:f");
2050
2051         // longest possible IPv6 length
2052         assert_eq!(
2053             Ipv6Addr::new(0x1111, 0x2222, 0x3333, 0x4444, 0x5555, 0x6666, 0x7777, 0x8888)
2054                 .to_string(),
2055             "1111:2222:3333:4444:5555:6666:7777:8888"
2056         );
2057         // padding
2058         assert_eq!(
2059             &format!("{:20}", Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8)),
2060             "1:2:3:4:5:6:7:8     "
2061         );
2062         assert_eq!(
2063             &format!("{:>20}", Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8)),
2064             "     1:2:3:4:5:6:7:8"
2065         );
2066
2067         // reduce a single run of zeros
2068         assert_eq!(
2069             "ae::ffff:102:304",
2070             Ipv6Addr::new(0xae, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304).to_string()
2071         );
2072
2073         // don't reduce just a single zero segment
2074         assert_eq!("1:2:3:4:5:6:0:8", Ipv6Addr::new(1, 2, 3, 4, 5, 6, 0, 8).to_string());
2075
2076         // 'any' address
2077         assert_eq!("::", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).to_string());
2078
2079         // loopback address
2080         assert_eq!("::1", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_string());
2081
2082         // ends in zeros
2083         assert_eq!("1::", Ipv6Addr::new(1, 0, 0, 0, 0, 0, 0, 0).to_string());
2084
2085         // two runs of zeros, second one is longer
2086         assert_eq!("1:0:0:4::8", Ipv6Addr::new(1, 0, 0, 4, 0, 0, 0, 8).to_string());
2087
2088         // two runs of zeros, equal length
2089         assert_eq!("1::4:5:0:0:8", Ipv6Addr::new(1, 0, 0, 4, 5, 0, 0, 8).to_string());
2090     }
2091
2092     #[test]
2093     fn ipv4_to_ipv6() {
2094         assert_eq!(
2095             Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678),
2096             Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_mapped()
2097         );
2098         assert_eq!(
2099             Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678),
2100             Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_compatible()
2101         );
2102     }
2103
2104     #[test]
2105     fn ipv6_to_ipv4_mapped() {
2106         assert_eq!(
2107             Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678).to_ipv4_mapped(),
2108             Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78))
2109         );
2110         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678).to_ipv4_mapped(), None);
2111     }
2112
2113     #[test]
2114     fn ipv6_to_ipv4() {
2115         assert_eq!(
2116             Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678).to_ipv4(),
2117             Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78))
2118         );
2119         assert_eq!(
2120             Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
2121             Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78))
2122         );
2123         assert_eq!(Ipv6Addr::new(0, 0, 1, 0, 0, 0, 0x1234, 0x5678).to_ipv4(), None);
2124     }
2125
2126     #[test]
2127     fn ip_properties() {
2128         macro_rules! ip {
2129             ($s:expr) => {
2130                 IpAddr::from_str($s).unwrap()
2131             };
2132         }
2133
2134         macro_rules! check {
2135             ($s:expr) => {
2136                 check!($s, 0);
2137             };
2138
2139             ($s:expr, $mask:expr) => {{
2140                 let unspec: u8 = 1 << 0;
2141                 let loopback: u8 = 1 << 1;
2142                 let global: u8 = 1 << 2;
2143                 let multicast: u8 = 1 << 3;
2144                 let doc: u8 = 1 << 4;
2145
2146                 if ($mask & unspec) == unspec {
2147                     assert!(ip!($s).is_unspecified());
2148                 } else {
2149                     assert!(!ip!($s).is_unspecified());
2150                 }
2151
2152                 if ($mask & loopback) == loopback {
2153                     assert!(ip!($s).is_loopback());
2154                 } else {
2155                     assert!(!ip!($s).is_loopback());
2156                 }
2157
2158                 if ($mask & global) == global {
2159                     assert!(ip!($s).is_global());
2160                 } else {
2161                     assert!(!ip!($s).is_global());
2162                 }
2163
2164                 if ($mask & multicast) == multicast {
2165                     assert!(ip!($s).is_multicast());
2166                 } else {
2167                     assert!(!ip!($s).is_multicast());
2168                 }
2169
2170                 if ($mask & doc) == doc {
2171                     assert!(ip!($s).is_documentation());
2172                 } else {
2173                     assert!(!ip!($s).is_documentation());
2174                 }
2175             }};
2176         }
2177
2178         let unspec: u8 = 1 << 0;
2179         let loopback: u8 = 1 << 1;
2180         let global: u8 = 1 << 2;
2181         let multicast: u8 = 1 << 3;
2182         let doc: u8 = 1 << 4;
2183
2184         check!("0.0.0.0", unspec);
2185         check!("0.0.0.1");
2186         check!("0.1.0.0");
2187         check!("10.9.8.7");
2188         check!("127.1.2.3", loopback);
2189         check!("172.31.254.253");
2190         check!("169.254.253.242");
2191         check!("192.0.2.183", doc);
2192         check!("192.1.2.183", global);
2193         check!("192.168.254.253");
2194         check!("198.51.100.0", doc);
2195         check!("203.0.113.0", doc);
2196         check!("203.2.113.0", global);
2197         check!("224.0.0.0", global | multicast);
2198         check!("239.255.255.255", global | multicast);
2199         check!("255.255.255.255");
2200         // make sure benchmarking addresses are not global
2201         check!("198.18.0.0");
2202         check!("198.18.54.2");
2203         check!("198.19.255.255");
2204         // make sure addresses reserved for protocol assignment are not global
2205         check!("192.0.0.0");
2206         check!("192.0.0.255");
2207         check!("192.0.0.100");
2208         // make sure reserved addresses are not global
2209         check!("240.0.0.0");
2210         check!("251.54.1.76");
2211         check!("254.255.255.255");
2212         // make sure shared addresses are not global
2213         check!("100.64.0.0");
2214         check!("100.127.255.255");
2215         check!("100.100.100.0");
2216
2217         check!("::", unspec);
2218         check!("::1", loopback);
2219         check!("::0.0.0.2", global);
2220         check!("1::", global);
2221         check!("fc00::");
2222         check!("fdff:ffff::");
2223         check!("fe80:ffff::");
2224         check!("febf:ffff::");
2225         check!("fec0::", global);
2226         check!("ff01::", multicast);
2227         check!("ff02::", multicast);
2228         check!("ff03::", multicast);
2229         check!("ff04::", multicast);
2230         check!("ff05::", multicast);
2231         check!("ff08::", multicast);
2232         check!("ff0e::", global | multicast);
2233         check!("2001:db8:85a3::8a2e:370:7334", doc);
2234         check!("102:304:506:708:90a:b0c:d0e:f10", global);
2235     }
2236
2237     #[test]
2238     fn ipv4_properties() {
2239         macro_rules! ip {
2240             ($s:expr) => {
2241                 Ipv4Addr::from_str($s).unwrap()
2242             };
2243         }
2244
2245         macro_rules! check {
2246             ($s:expr) => {
2247                 check!($s, 0);
2248             };
2249
2250             ($s:expr, $mask:expr) => {{
2251                 let unspec: u16 = 1 << 0;
2252                 let loopback: u16 = 1 << 1;
2253                 let private: u16 = 1 << 2;
2254                 let link_local: u16 = 1 << 3;
2255                 let global: u16 = 1 << 4;
2256                 let multicast: u16 = 1 << 5;
2257                 let broadcast: u16 = 1 << 6;
2258                 let documentation: u16 = 1 << 7;
2259                 let benchmarking: u16 = 1 << 8;
2260                 let ietf_protocol_assignment: u16 = 1 << 9;
2261                 let reserved: u16 = 1 << 10;
2262                 let shared: u16 = 1 << 11;
2263
2264                 if ($mask & unspec) == unspec {
2265                     assert!(ip!($s).is_unspecified());
2266                 } else {
2267                     assert!(!ip!($s).is_unspecified());
2268                 }
2269
2270                 if ($mask & loopback) == loopback {
2271                     assert!(ip!($s).is_loopback());
2272                 } else {
2273                     assert!(!ip!($s).is_loopback());
2274                 }
2275
2276                 if ($mask & private) == private {
2277                     assert!(ip!($s).is_private());
2278                 } else {
2279                     assert!(!ip!($s).is_private());
2280                 }
2281
2282                 if ($mask & link_local) == link_local {
2283                     assert!(ip!($s).is_link_local());
2284                 } else {
2285                     assert!(!ip!($s).is_link_local());
2286                 }
2287
2288                 if ($mask & global) == global {
2289                     assert!(ip!($s).is_global());
2290                 } else {
2291                     assert!(!ip!($s).is_global());
2292                 }
2293
2294                 if ($mask & multicast) == multicast {
2295                     assert!(ip!($s).is_multicast());
2296                 } else {
2297                     assert!(!ip!($s).is_multicast());
2298                 }
2299
2300                 if ($mask & broadcast) == broadcast {
2301                     assert!(ip!($s).is_broadcast());
2302                 } else {
2303                     assert!(!ip!($s).is_broadcast());
2304                 }
2305
2306                 if ($mask & documentation) == documentation {
2307                     assert!(ip!($s).is_documentation());
2308                 } else {
2309                     assert!(!ip!($s).is_documentation());
2310                 }
2311
2312                 if ($mask & benchmarking) == benchmarking {
2313                     assert!(ip!($s).is_benchmarking());
2314                 } else {
2315                     assert!(!ip!($s).is_benchmarking());
2316                 }
2317
2318                 if ($mask & ietf_protocol_assignment) == ietf_protocol_assignment {
2319                     assert!(ip!($s).is_ietf_protocol_assignment());
2320                 } else {
2321                     assert!(!ip!($s).is_ietf_protocol_assignment());
2322                 }
2323
2324                 if ($mask & reserved) == reserved {
2325                     assert!(ip!($s).is_reserved());
2326                 } else {
2327                     assert!(!ip!($s).is_reserved());
2328                 }
2329
2330                 if ($mask & shared) == shared {
2331                     assert!(ip!($s).is_shared());
2332                 } else {
2333                     assert!(!ip!($s).is_shared());
2334                 }
2335             }};
2336         }
2337
2338         let unspec: u16 = 1 << 0;
2339         let loopback: u16 = 1 << 1;
2340         let private: u16 = 1 << 2;
2341         let link_local: u16 = 1 << 3;
2342         let global: u16 = 1 << 4;
2343         let multicast: u16 = 1 << 5;
2344         let broadcast: u16 = 1 << 6;
2345         let documentation: u16 = 1 << 7;
2346         let benchmarking: u16 = 1 << 8;
2347         let ietf_protocol_assignment: u16 = 1 << 9;
2348         let reserved: u16 = 1 << 10;
2349         let shared: u16 = 1 << 11;
2350
2351         check!("0.0.0.0", unspec);
2352         check!("0.0.0.1");
2353         check!("0.1.0.0");
2354         check!("10.9.8.7", private);
2355         check!("127.1.2.3", loopback);
2356         check!("172.31.254.253", private);
2357         check!("169.254.253.242", link_local);
2358         check!("192.0.2.183", documentation);
2359         check!("192.1.2.183", global);
2360         check!("192.168.254.253", private);
2361         check!("198.51.100.0", documentation);
2362         check!("203.0.113.0", documentation);
2363         check!("203.2.113.0", global);
2364         check!("224.0.0.0", global | multicast);
2365         check!("239.255.255.255", global | multicast);
2366         check!("255.255.255.255", broadcast);
2367         check!("198.18.0.0", benchmarking);
2368         check!("198.18.54.2", benchmarking);
2369         check!("198.19.255.255", benchmarking);
2370         check!("192.0.0.0", ietf_protocol_assignment);
2371         check!("192.0.0.255", ietf_protocol_assignment);
2372         check!("192.0.0.100", ietf_protocol_assignment);
2373         check!("240.0.0.0", reserved);
2374         check!("251.54.1.76", reserved);
2375         check!("254.255.255.255", reserved);
2376         check!("100.64.0.0", shared);
2377         check!("100.127.255.255", shared);
2378         check!("100.100.100.0", shared);
2379     }
2380
2381     #[test]
2382     fn ipv6_properties() {
2383         macro_rules! ip {
2384             ($s:expr) => {
2385                 Ipv6Addr::from_str($s).unwrap()
2386             };
2387         }
2388
2389         macro_rules! check {
2390             ($s:expr, &[$($octet:expr),*], $mask:expr) => {
2391                 assert_eq!($s, ip!($s).to_string());
2392                 let octets = &[$($octet),*];
2393                 assert_eq!(&ip!($s).octets(), octets);
2394                 assert_eq!(Ipv6Addr::from(*octets), ip!($s));
2395
2396                 let unspecified: u16 = 1 << 0;
2397                 let loopback: u16 = 1 << 1;
2398                 let unique_local: u16 = 1 << 2;
2399                 let global: u16 = 1 << 3;
2400                 let unicast_link_local: u16 = 1 << 4;
2401                 let unicast_link_local_strict: u16 = 1 << 5;
2402                 let unicast_site_local: u16 = 1 << 6;
2403                 let unicast_global: u16 = 1 << 7;
2404                 let documentation: u16 = 1 << 8;
2405                 let multicast_interface_local: u16 = 1 << 9;
2406                 let multicast_link_local: u16 = 1 << 10;
2407                 let multicast_realm_local: u16 = 1 << 11;
2408                 let multicast_admin_local: u16 = 1 << 12;
2409                 let multicast_site_local: u16 = 1 << 13;
2410                 let multicast_organization_local: u16 = 1 << 14;
2411                 let multicast_global: u16 = 1 << 15;
2412                 let multicast: u16 = multicast_interface_local
2413                     | multicast_admin_local
2414                     | multicast_global
2415                     | multicast_link_local
2416                     | multicast_realm_local
2417                     | multicast_site_local
2418                     | multicast_organization_local;
2419
2420                 if ($mask & unspecified) == unspecified {
2421                     assert!(ip!($s).is_unspecified());
2422                 } else {
2423                     assert!(!ip!($s).is_unspecified());
2424                 }
2425                 if ($mask & loopback) == loopback {
2426                     assert!(ip!($s).is_loopback());
2427                 } else {
2428                     assert!(!ip!($s).is_loopback());
2429                 }
2430                 if ($mask & unique_local) == unique_local {
2431                     assert!(ip!($s).is_unique_local());
2432                 } else {
2433                     assert!(!ip!($s).is_unique_local());
2434                 }
2435                 if ($mask & global) == global {
2436                     assert!(ip!($s).is_global());
2437                 } else {
2438                     assert!(!ip!($s).is_global());
2439                 }
2440                 if ($mask & unicast_link_local) == unicast_link_local {
2441                     assert!(ip!($s).is_unicast_link_local());
2442                 } else {
2443                     assert!(!ip!($s).is_unicast_link_local());
2444                 }
2445                 if ($mask & unicast_link_local_strict) == unicast_link_local_strict {
2446                     assert!(ip!($s).is_unicast_link_local_strict());
2447                 } else {
2448                     assert!(!ip!($s).is_unicast_link_local_strict());
2449                 }
2450                 if ($mask & unicast_site_local) == unicast_site_local {
2451                     assert!(ip!($s).is_unicast_site_local());
2452                 } else {
2453                     assert!(!ip!($s).is_unicast_site_local());
2454                 }
2455                 if ($mask & unicast_global) == unicast_global {
2456                     assert!(ip!($s).is_unicast_global());
2457                 } else {
2458                     assert!(!ip!($s).is_unicast_global());
2459                 }
2460                 if ($mask & documentation) == documentation {
2461                     assert!(ip!($s).is_documentation());
2462                 } else {
2463                     assert!(!ip!($s).is_documentation());
2464                 }
2465                 if ($mask & multicast) != 0 {
2466                     assert!(ip!($s).multicast_scope().is_some());
2467                     assert!(ip!($s).is_multicast());
2468                 } else {
2469                     assert!(ip!($s).multicast_scope().is_none());
2470                     assert!(!ip!($s).is_multicast());
2471                 }
2472                 if ($mask & multicast_interface_local) == multicast_interface_local {
2473                     assert_eq!(ip!($s).multicast_scope().unwrap(),
2474                                Ipv6MulticastScope::InterfaceLocal);
2475                 }
2476                 if ($mask & multicast_link_local) == multicast_link_local {
2477                     assert_eq!(ip!($s).multicast_scope().unwrap(),
2478                                Ipv6MulticastScope::LinkLocal);
2479                 }
2480                 if ($mask & multicast_realm_local) == multicast_realm_local {
2481                     assert_eq!(ip!($s).multicast_scope().unwrap(),
2482                                Ipv6MulticastScope::RealmLocal);
2483                 }
2484                 if ($mask & multicast_admin_local) == multicast_admin_local {
2485                     assert_eq!(ip!($s).multicast_scope().unwrap(),
2486                                Ipv6MulticastScope::AdminLocal);
2487                 }
2488                 if ($mask & multicast_site_local) == multicast_site_local {
2489                     assert_eq!(ip!($s).multicast_scope().unwrap(),
2490                                Ipv6MulticastScope::SiteLocal);
2491                 }
2492                 if ($mask & multicast_organization_local) == multicast_organization_local {
2493                     assert_eq!(ip!($s).multicast_scope().unwrap(),
2494                                Ipv6MulticastScope::OrganizationLocal);
2495                 }
2496                 if ($mask & multicast_global) == multicast_global {
2497                     assert_eq!(ip!($s).multicast_scope().unwrap(),
2498                                Ipv6MulticastScope::Global);
2499                 }
2500             }
2501         }
2502
2503         let unspecified: u16 = 1 << 0;
2504         let loopback: u16 = 1 << 1;
2505         let unique_local: u16 = 1 << 2;
2506         let global: u16 = 1 << 3;
2507         let unicast_link_local: u16 = 1 << 4;
2508         let unicast_link_local_strict: u16 = 1 << 5;
2509         let unicast_site_local: u16 = 1 << 6;
2510         let unicast_global: u16 = 1 << 7;
2511         let documentation: u16 = 1 << 8;
2512         let multicast_interface_local: u16 = 1 << 9;
2513         let multicast_link_local: u16 = 1 << 10;
2514         let multicast_realm_local: u16 = 1 << 11;
2515         let multicast_admin_local: u16 = 1 << 12;
2516         let multicast_site_local: u16 = 1 << 13;
2517         let multicast_organization_local: u16 = 1 << 14;
2518         let multicast_global: u16 = 1 << 15;
2519
2520         check!("::", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], unspecified);
2521
2522         check!("::1", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], loopback);
2523
2524         check!(
2525             "::0.0.0.2",
2526             &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2],
2527             global | unicast_global
2528         );
2529
2530         check!("1::", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], global | unicast_global);
2531
2532         check!("fc00::", &[0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], unique_local);
2533
2534         check!(
2535             "fdff:ffff::",
2536             &[0xfd, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2537             unique_local
2538         );
2539
2540         check!(
2541             "fe80:ffff::",
2542             &[0xfe, 0x80, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2543             unicast_link_local
2544         );
2545
2546         check!(
2547             "fe80::",
2548             &[0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2549             unicast_link_local | unicast_link_local_strict
2550         );
2551
2552         check!(
2553             "febf:ffff::",
2554             &[0xfe, 0xbf, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2555             unicast_link_local
2556         );
2557
2558         check!(
2559             "febf::",
2560             &[0xfe, 0xbf, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2561             unicast_link_local
2562         );
2563
2564         check!(
2565             "febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
2566             &[
2567                 0xfe, 0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2568                 0xff, 0xff
2569             ],
2570             unicast_link_local
2571         );
2572
2573         check!(
2574             "fe80::ffff:ffff:ffff:ffff",
2575             &[
2576                 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
2577                 0xff, 0xff
2578             ],
2579             unicast_link_local | unicast_link_local_strict
2580         );
2581
2582         check!(
2583             "fe80:0:0:1::",
2584             &[0xfe, 0x80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
2585             unicast_link_local
2586         );
2587
2588         check!(
2589             "fec0::",
2590             &[0xfe, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2591             unicast_site_local | unicast_global | global
2592         );
2593
2594         check!(
2595             "ff01::",
2596             &[0xff, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2597             multicast_interface_local
2598         );
2599
2600         check!(
2601             "ff02::",
2602             &[0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2603             multicast_link_local
2604         );
2605
2606         check!(
2607             "ff03::",
2608             &[0xff, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2609             multicast_realm_local
2610         );
2611
2612         check!(
2613             "ff04::",
2614             &[0xff, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2615             multicast_admin_local
2616         );
2617
2618         check!(
2619             "ff05::",
2620             &[0xff, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2621             multicast_site_local
2622         );
2623
2624         check!(
2625             "ff08::",
2626             &[0xff, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2627             multicast_organization_local
2628         );
2629
2630         check!(
2631             "ff0e::",
2632             &[0xff, 0xe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2633             multicast_global | global
2634         );
2635
2636         check!(
2637             "2001:db8:85a3::8a2e:370:7334",
2638             &[0x20, 1, 0xd, 0xb8, 0x85, 0xa3, 0, 0, 0, 0, 0x8a, 0x2e, 3, 0x70, 0x73, 0x34],
2639             documentation
2640         );
2641
2642         check!(
2643             "102:304:506:708:90a:b0c:d0e:f10",
2644             &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
2645             global | unicast_global
2646         );
2647     }
2648
2649     #[test]
2650     fn to_socket_addr_socketaddr() {
2651         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 12345);
2652         assert_eq!(Ok(vec![a]), tsa(a));
2653     }
2654
2655     #[test]
2656     fn test_ipv4_to_int() {
2657         let a = Ipv4Addr::new(0x11, 0x22, 0x33, 0x44);
2658         assert_eq!(u32::from(a), 0x11223344);
2659     }
2660
2661     #[test]
2662     fn test_int_to_ipv4() {
2663         let a = Ipv4Addr::new(0x11, 0x22, 0x33, 0x44);
2664         assert_eq!(Ipv4Addr::from(0x11223344), a);
2665     }
2666
2667     #[test]
2668     fn test_ipv6_to_int() {
2669         let a = Ipv6Addr::new(0x1122, 0x3344, 0x5566, 0x7788, 0x99aa, 0xbbcc, 0xddee, 0xff11);
2670         assert_eq!(u128::from(a), 0x112233445566778899aabbccddeeff11u128);
2671     }
2672
2673     #[test]
2674     fn test_int_to_ipv6() {
2675         let a = Ipv6Addr::new(0x1122, 0x3344, 0x5566, 0x7788, 0x99aa, 0xbbcc, 0xddee, 0xff11);
2676         assert_eq!(Ipv6Addr::from(0x112233445566778899aabbccddeeff11u128), a);
2677     }
2678
2679     #[test]
2680     fn ipv4_from_constructors() {
2681         assert_eq!(Ipv4Addr::LOCALHOST, Ipv4Addr::new(127, 0, 0, 1));
2682         assert!(Ipv4Addr::LOCALHOST.is_loopback());
2683         assert_eq!(Ipv4Addr::UNSPECIFIED, Ipv4Addr::new(0, 0, 0, 0));
2684         assert!(Ipv4Addr::UNSPECIFIED.is_unspecified());
2685         assert_eq!(Ipv4Addr::BROADCAST, Ipv4Addr::new(255, 255, 255, 255));
2686         assert!(Ipv4Addr::BROADCAST.is_broadcast());
2687     }
2688
2689     #[test]
2690     fn ipv6_from_contructors() {
2691         assert_eq!(Ipv6Addr::LOCALHOST, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
2692         assert!(Ipv6Addr::LOCALHOST.is_loopback());
2693         assert_eq!(Ipv6Addr::UNSPECIFIED, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
2694         assert!(Ipv6Addr::UNSPECIFIED.is_unspecified());
2695     }
2696
2697     #[test]
2698     fn ipv4_from_octets() {
2699         assert_eq!(Ipv4Addr::from([127, 0, 0, 1]), Ipv4Addr::new(127, 0, 0, 1))
2700     }
2701
2702     #[test]
2703     fn ipv6_from_segments() {
2704         let from_u16s =
2705             Ipv6Addr::from([0x0011, 0x2233, 0x4455, 0x6677, 0x8899, 0xaabb, 0xccdd, 0xeeff]);
2706         let new = Ipv6Addr::new(0x0011, 0x2233, 0x4455, 0x6677, 0x8899, 0xaabb, 0xccdd, 0xeeff);
2707         assert_eq!(new, from_u16s);
2708     }
2709
2710     #[test]
2711     fn ipv6_from_octets() {
2712         let from_u16s =
2713             Ipv6Addr::from([0x0011, 0x2233, 0x4455, 0x6677, 0x8899, 0xaabb, 0xccdd, 0xeeff]);
2714         let from_u8s = Ipv6Addr::from([
2715             0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
2716             0xee, 0xff,
2717         ]);
2718         assert_eq!(from_u16s, from_u8s);
2719     }
2720
2721     #[test]
2722     fn cmp() {
2723         let v41 = Ipv4Addr::new(100, 64, 3, 3);
2724         let v42 = Ipv4Addr::new(192, 0, 2, 2);
2725         let v61 = "2001:db8:f00::1002".parse::<Ipv6Addr>().unwrap();
2726         let v62 = "2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap();
2727         assert!(v41 < v42);
2728         assert!(v61 < v62);
2729
2730         assert_eq!(v41, IpAddr::V4(v41));
2731         assert_eq!(v61, IpAddr::V6(v61));
2732         assert!(v41 != IpAddr::V4(v42));
2733         assert!(v61 != IpAddr::V6(v62));
2734
2735         assert!(v41 < IpAddr::V4(v42));
2736         assert!(v61 < IpAddr::V6(v62));
2737         assert!(IpAddr::V4(v41) < v42);
2738         assert!(IpAddr::V6(v61) < v62);
2739
2740         assert!(v41 < IpAddr::V6(v61));
2741         assert!(IpAddr::V4(v41) < v61);
2742     }
2743
2744     #[test]
2745     fn is_v4() {
2746         let ip = IpAddr::V4(Ipv4Addr::new(100, 64, 3, 3));
2747         assert!(ip.is_ipv4());
2748         assert!(!ip.is_ipv6());
2749     }
2750
2751     #[test]
2752     fn is_v6() {
2753         let ip = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678));
2754         assert!(!ip.is_ipv4());
2755         assert!(ip.is_ipv6());
2756     }
2757 }