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