]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/ip.rs
Auto merge of #43748 - RalfJung:mir-validate2, r=arielb1
[rust.git] / src / libstd / net / ip.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![unstable(feature = "ip", reason = "extra functionality has not been \
12                                       scrutinized to the level that it should \
13                                       be stable",
14             issue = "27709")]
15
16 use cmp::Ordering;
17 use fmt;
18 use hash;
19 use mem;
20 use net::{hton, ntoh};
21 use sys::net::netc as c;
22 use sys_common::{AsInner, FromInner};
23
24 /// An IP address, either IPv4 or IPv6.
25 ///
26 /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
27 /// respective documentation for more details.
28 ///
29 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
30 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
31 ///
32 /// # Examples
33 ///
34 /// ```
35 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
36 ///
37 /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
38 /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
39 ///
40 /// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
41 /// assert_eq!("::1".parse(), Ok(localhost_v6));
42 ///
43 /// assert_eq!(localhost_v4.is_ipv6(), false);
44 /// assert_eq!(localhost_v4.is_ipv4(), true);
45 /// ```
46 #[stable(feature = "ip_addr", since = "1.7.0")]
47 #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
48 pub enum IpAddr {
49     /// An IPv4 address.
50     #[stable(feature = "ip_addr", since = "1.7.0")]
51     V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
52     /// An IPv6 address.
53     #[stable(feature = "ip_addr", since = "1.7.0")]
54     V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
55 }
56
57 /// An IPv4 address.
58 ///
59 /// IPv4 addresses are defined as 32-bit integers in [IETF RFC 791].
60 /// They are usually represented as four octets.
61 ///
62 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
63 ///
64 /// [IETF RFC 791]: https://tools.ietf.org/html/rfc791
65 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
66 ///
67 /// # Textual representation
68 ///
69 /// `Ipv4Addr` provides a [`FromStr`] implementation. The four octets are in decimal
70 /// notation, divided by `.` (this is called "dot-decimal notation").
71 ///
72 /// [`FromStr`]: ../../std/str/trait.FromStr.html
73 ///
74 /// # Examples
75 ///
76 /// ```
77 /// use std::net::Ipv4Addr;
78 ///
79 /// let localhost = Ipv4Addr::new(127, 0, 0, 1);
80 /// assert_eq!("127.0.0.1".parse(), Ok(localhost));
81 /// assert_eq!(localhost.is_loopback(), true);
82 /// ```
83 #[derive(Copy)]
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct Ipv4Addr {
86     inner: c::in_addr,
87 }
88
89 /// An IPv6 address.
90 ///
91 /// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
92 /// They are usually represented as eight 16-bit segments.
93 ///
94 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
95 ///
96 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
97 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
98 ///
99 /// # Textual representation
100 ///
101 /// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
102 /// an IPv6 address in text, but in general, each segments is written in hexadecimal
103 /// notation, and segments are separated by `:`. For more information, see
104 /// [IETF RFC 5952].
105 ///
106 /// [`FromStr`]: ../../std/str/trait.FromStr.html
107 /// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
108 ///
109 /// # Examples
110 ///
111 /// ```
112 /// use std::net::Ipv6Addr;
113 ///
114 /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
115 /// assert_eq!("::1".parse(), Ok(localhost));
116 /// assert_eq!(localhost.is_loopback(), true);
117 /// ```
118 #[derive(Copy)]
119 #[stable(feature = "rust1", since = "1.0.0")]
120 pub struct Ipv6Addr {
121     inner: c::in6_addr,
122 }
123
124 #[allow(missing_docs)]
125 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
126 pub enum Ipv6MulticastScope {
127     InterfaceLocal,
128     LinkLocal,
129     RealmLocal,
130     AdminLocal,
131     SiteLocal,
132     OrganizationLocal,
133     Global
134 }
135
136 impl IpAddr {
137     /// Returns [`true`] for the special 'unspecified' address.
138     ///
139     /// See the documentation for [`Ipv4Addr::is_unspecified`][IPv4] and
140     /// [`Ipv6Addr::is_unspecified`][IPv6] for more details.
141     ///
142     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_unspecified
143     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_unspecified
144     /// [`true`]: ../../std/primitive.bool.html
145     ///
146     /// # Examples
147     ///
148     /// ```
149     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
150     ///
151     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
152     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
153     /// ```
154     #[stable(feature = "ip_shared", since = "1.12.0")]
155     pub fn is_unspecified(&self) -> bool {
156         match *self {
157             IpAddr::V4(ref a) => a.is_unspecified(),
158             IpAddr::V6(ref a) => a.is_unspecified(),
159         }
160     }
161
162     /// Returns [`true`] if this is a loopback address.
163     ///
164     /// See the documentation for [`Ipv4Addr::is_loopback`][IPv4] and
165     /// [`Ipv6Addr::is_loopback`][IPv6] for more details.
166     ///
167     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_loopback
168     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_loopback
169     /// [`true`]: ../../std/primitive.bool.html
170     ///
171     /// # Examples
172     ///
173     /// ```
174     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
175     ///
176     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
177     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
178     /// ```
179     #[stable(feature = "ip_shared", since = "1.12.0")]
180     pub fn is_loopback(&self) -> bool {
181         match *self {
182             IpAddr::V4(ref a) => a.is_loopback(),
183             IpAddr::V6(ref a) => a.is_loopback(),
184         }
185     }
186
187     /// Returns [`true`] if the address appears to be globally routable.
188     ///
189     /// See the documentation for [`Ipv4Addr::is_global`][IPv4] and
190     /// [`Ipv6Addr::is_global`][IPv6] for more details.
191     ///
192     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_global
193     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_global
194     /// [`true`]: ../../std/primitive.bool.html
195     ///
196     /// # Examples
197     ///
198     /// ```
199     /// #![feature(ip)]
200     ///
201     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
202     ///
203     /// fn main() {
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(),
206     ///                true);
207     /// }
208     /// ```
209     pub fn is_global(&self) -> bool {
210         match *self {
211             IpAddr::V4(ref a) => a.is_global(),
212             IpAddr::V6(ref a) => a.is_global(),
213         }
214     }
215
216     /// Returns [`true`] if this is a multicast address.
217     ///
218     /// See the documentation for [`Ipv4Addr::is_multicast`][IPv4] and
219     /// [`Ipv6Addr::is_multicast`][IPv6] for more details.
220     ///
221     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_multicast
222     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_multicast
223     /// [`true`]: ../../std/primitive.bool.html
224     ///
225     /// # Examples
226     ///
227     /// ```
228     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
229     ///
230     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
231     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
232     /// ```
233     #[stable(feature = "ip_shared", since = "1.12.0")]
234     pub fn is_multicast(&self) -> bool {
235         match *self {
236             IpAddr::V4(ref a) => a.is_multicast(),
237             IpAddr::V6(ref a) => a.is_multicast(),
238         }
239     }
240
241     /// Returns [`true`] if this address is in a range designated for documentation.
242     ///
243     /// See the documentation for [`Ipv4Addr::is_documentation`][IPv4] and
244     /// [`Ipv6Addr::is_documentation`][IPv6] for more details.
245     ///
246     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_documentation
247     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_documentation
248     /// [`true`]: ../../std/primitive.bool.html
249     ///
250     /// # Examples
251     ///
252     /// ```
253     /// #![feature(ip)]
254     ///
255     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
256     ///
257     /// fn main() {
258     ///     assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
259     ///     assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0))
260     ///                       .is_documentation(), true);
261     /// }
262     /// ```
263     pub fn is_documentation(&self) -> bool {
264         match *self {
265             IpAddr::V4(ref a) => a.is_documentation(),
266             IpAddr::V6(ref a) => a.is_documentation(),
267         }
268     }
269
270     /// Returns [`true`] if this address is an [IPv4 address], and [`false`] otherwise.
271     ///
272     /// [`true`]: ../../std/primitive.bool.html
273     /// [`false`]: ../../std/primitive.bool.html
274     /// [IPv4 address]: #variant.V4
275     ///
276     /// # Examples
277     ///
278     /// ```
279     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
280     ///
281     /// fn main() {
282     ///     assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
283     ///     assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(),
284     ///                false);
285     /// }
286     /// ```
287     #[stable(feature = "ipaddr_checker", since = "1.16.0")]
288     pub fn is_ipv4(&self) -> bool {
289         match *self {
290             IpAddr::V4(_) => true,
291             IpAddr::V6(_) => false,
292         }
293     }
294
295     /// Returns [`true`] if this address is an [IPv6 address], and [`false`] otherwise.
296     ///
297     /// [`true`]: ../../std/primitive.bool.html
298     /// [`false`]: ../../std/primitive.bool.html
299     /// [IPv6 address]: #variant.V6
300     ///
301     /// # Examples
302     ///
303     /// ```
304     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
305     ///
306     /// fn main() {
307     ///     assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
308     ///     assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(),
309     ///                true);
310     /// }
311     /// ```
312     #[stable(feature = "ipaddr_checker", since = "1.16.0")]
313     pub fn is_ipv6(&self) -> bool {
314         match *self {
315             IpAddr::V4(_) => false,
316             IpAddr::V6(_) => true,
317         }
318     }
319 }
320
321 impl Ipv4Addr {
322     /// Creates a new IPv4 address from four eight-bit octets.
323     ///
324     /// The result will represent the IP address `a`.`b`.`c`.`d`.
325     ///
326     /// # Examples
327     ///
328     /// ```
329     /// use std::net::Ipv4Addr;
330     ///
331     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
332     /// ```
333     #[stable(feature = "rust1", since = "1.0.0")]
334     pub fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
335         Ipv4Addr {
336             inner: c::in_addr {
337                 s_addr: hton(((a as u32) << 24) |
338                              ((b as u32) << 16) |
339                              ((c as u32) <<  8) |
340                               (d as u32)),
341             }
342         }
343     }
344
345     /// Returns the four eight-bit integers that make up this address.
346     ///
347     /// # Examples
348     ///
349     /// ```
350     /// use std::net::Ipv4Addr;
351     ///
352     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
353     /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
354     /// ```
355     #[stable(feature = "rust1", since = "1.0.0")]
356     pub fn octets(&self) -> [u8; 4] {
357         let bits = ntoh(self.inner.s_addr);
358         [(bits >> 24) as u8, (bits >> 16) as u8, (bits >> 8) as u8, bits as u8]
359     }
360
361     /// Returns [`true`] for the special 'unspecified' address (0.0.0.0).
362     ///
363     /// This property is defined in _UNIX Network Programming, Second Edition_,
364     /// W. Richard Stevens, p. 891; see also [ip7].
365     ///
366     /// [ip7]: http://man7.org/linux/man-pages/man7/ip.7.html
367     /// [`true`]: ../../std/primitive.bool.html
368     ///
369     /// # Examples
370     ///
371     /// ```
372     /// use std::net::Ipv4Addr;
373     ///
374     /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
375     /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
376     /// ```
377     #[stable(feature = "ip_shared", since = "1.12.0")]
378     pub fn is_unspecified(&self) -> bool {
379         self.inner.s_addr == 0
380     }
381
382     /// Returns [`true`] if this is a loopback address (127.0.0.0/8).
383     ///
384     /// This property is defined by [IETF RFC 1122].
385     ///
386     /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
387     /// [`true`]: ../../std/primitive.bool.html
388     ///
389     /// # Examples
390     ///
391     /// ```
392     /// use std::net::Ipv4Addr;
393     ///
394     /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
395     /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
396     /// ```
397     #[stable(since = "1.7.0", feature = "ip_17")]
398     pub fn is_loopback(&self) -> bool {
399         self.octets()[0] == 127
400     }
401
402     /// Returns [`true`] if this is a private address.
403     ///
404     /// The private address ranges are defined in [IETF RFC 1918] and include:
405     ///
406     ///  - 10.0.0.0/8
407     ///  - 172.16.0.0/12
408     ///  - 192.168.0.0/16
409     ///
410     /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
411     /// [`true`]: ../../std/primitive.bool.html
412     ///
413     /// # Examples
414     ///
415     /// ```
416     /// use std::net::Ipv4Addr;
417     ///
418     /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
419     /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
420     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
421     /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
422     /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
423     /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
424     /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
425     /// ```
426     #[stable(since = "1.7.0", feature = "ip_17")]
427     pub fn is_private(&self) -> bool {
428         match (self.octets()[0], self.octets()[1]) {
429             (10, _) => true,
430             (172, b) if b >= 16 && b <= 31 => true,
431             (192, 168) => true,
432             _ => false
433         }
434     }
435
436     /// Returns [`true`] if the address is link-local (169.254.0.0/16).
437     ///
438     /// This property is defined by [IETF RFC 3927].
439     ///
440     /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
441     /// [`true`]: ../../std/primitive.bool.html
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// use std::net::Ipv4Addr;
447     ///
448     /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
449     /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
450     /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
451     /// ```
452     #[stable(since = "1.7.0", feature = "ip_17")]
453     pub fn is_link_local(&self) -> bool {
454         self.octets()[0] == 169 && self.octets()[1] == 254
455     }
456
457     /// Returns [`true`] if the address appears to be globally routable.
458     /// See [iana-ipv4-special-registry][ipv4-sr].
459     ///
460     /// The following return false:
461     ///
462     /// - private address (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16)
463     /// - the loopback address (127.0.0.0/8)
464     /// - the link-local address (169.254.0.0/16)
465     /// - the broadcast address (255.255.255.255/32)
466     /// - test addresses used for documentation (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24)
467     /// - the unspecified address (0.0.0.0)
468     ///
469     /// [ipv4-sr]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
470     /// [`true`]: ../../std/primitive.bool.html
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// #![feature(ip)]
476     ///
477     /// use std::net::Ipv4Addr;
478     ///
479     /// fn main() {
480     ///     assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
481     ///     assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
482     ///     assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
483     ///     assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_global(), false);
484     ///     assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
485     /// }
486     /// ```
487     pub fn is_global(&self) -> bool {
488         !self.is_private() && !self.is_loopback() && !self.is_link_local() &&
489         !self.is_broadcast() && !self.is_documentation() && !self.is_unspecified()
490     }
491
492     /// Returns [`true`] if this is a multicast address (224.0.0.0/4).
493     ///
494     /// Multicast addresses have a most significant octet between 224 and 239,
495     /// and is defined by [IETF RFC 5771].
496     ///
497     /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
498     /// [`true`]: ../../std/primitive.bool.html
499     ///
500     /// # Examples
501     ///
502     /// ```
503     /// use std::net::Ipv4Addr;
504     ///
505     /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
506     /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
507     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
508     /// ```
509     #[stable(since = "1.7.0", feature = "ip_17")]
510     pub fn is_multicast(&self) -> bool {
511         self.octets()[0] >= 224 && self.octets()[0] <= 239
512     }
513
514     /// Returns [`true`] if this is a broadcast address (255.255.255.255).
515     ///
516     /// A broadcast address has all octets set to 255 as defined in [IETF RFC 919].
517     ///
518     /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
519     /// [`true`]: ../../std/primitive.bool.html
520     ///
521     /// # Examples
522     ///
523     /// ```
524     /// use std::net::Ipv4Addr;
525     ///
526     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
527     /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
528     /// ```
529     #[stable(since = "1.7.0", feature = "ip_17")]
530     pub fn is_broadcast(&self) -> bool {
531         self.octets()[0] == 255 && self.octets()[1] == 255 &&
532         self.octets()[2] == 255 && self.octets()[3] == 255
533     }
534
535     /// Returns [`true`] if this address is in a range designated for documentation.
536     ///
537     /// This is defined in [IETF RFC 5737]:
538     ///
539     /// - 192.0.2.0/24 (TEST-NET-1)
540     /// - 198.51.100.0/24 (TEST-NET-2)
541     /// - 203.0.113.0/24 (TEST-NET-3)
542     ///
543     /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
544     /// [`true`]: ../../std/primitive.bool.html
545     ///
546     /// # Examples
547     ///
548     /// ```
549     /// use std::net::Ipv4Addr;
550     ///
551     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
552     /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
553     /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
554     /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
555     /// ```
556     #[stable(since = "1.7.0", feature = "ip_17")]
557     pub fn is_documentation(&self) -> bool {
558         match(self.octets()[0], self.octets()[1], self.octets()[2], self.octets()[3]) {
559             (192, 0, 2, _) => true,
560             (198, 51, 100, _) => true,
561             (203, 0, 113, _) => true,
562             _ => false
563         }
564     }
565
566     /// Converts this address to an IPv4-compatible [IPv6 address].
567     ///
568     /// a.b.c.d becomes ::a.b.c.d
569     ///
570     /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
571     ///
572     /// # Examples
573     ///
574     /// ```
575     /// use std::net::{Ipv4Addr, Ipv6Addr};
576     ///
577     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
578     ///            Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 767));
579     /// ```
580     #[stable(feature = "rust1", since = "1.0.0")]
581     pub fn to_ipv6_compatible(&self) -> Ipv6Addr {
582         Ipv6Addr::new(0, 0, 0, 0, 0, 0,
583                       ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
584                       ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
585     }
586
587     /// Converts this address to an IPv4-mapped [IPv6 address].
588     ///
589     /// a.b.c.d becomes ::ffff:a.b.c.d
590     ///
591     /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
592     ///
593     /// # Examples
594     ///
595     /// ```
596     /// use std::net::{Ipv4Addr, Ipv6Addr};
597     ///
598     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
599     ///            Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 49152, 767));
600     /// ```
601     #[stable(feature = "rust1", since = "1.0.0")]
602     pub fn to_ipv6_mapped(&self) -> Ipv6Addr {
603         Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff,
604                       ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
605                       ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
606     }
607 }
608
609 #[stable(feature = "ip_addr", since = "1.7.0")]
610 impl fmt::Display for IpAddr {
611     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
612         match *self {
613             IpAddr::V4(ref a) => a.fmt(fmt),
614             IpAddr::V6(ref a) => a.fmt(fmt),
615         }
616     }
617 }
618
619 #[stable(feature = "ip_from_ip", since = "1.16.0")]
620 impl From<Ipv4Addr> for IpAddr {
621     fn from(ipv4: Ipv4Addr) -> IpAddr {
622         IpAddr::V4(ipv4)
623     }
624 }
625
626 #[stable(feature = "ip_from_ip", since = "1.16.0")]
627 impl From<Ipv6Addr> for IpAddr {
628     fn from(ipv6: Ipv6Addr) -> IpAddr {
629         IpAddr::V6(ipv6)
630     }
631 }
632
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl fmt::Display for Ipv4Addr {
635     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
636         let octets = self.octets();
637         write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
638     }
639 }
640
641 #[stable(feature = "rust1", since = "1.0.0")]
642 impl fmt::Debug for Ipv4Addr {
643     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
644         fmt::Display::fmt(self, fmt)
645     }
646 }
647
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl Clone for Ipv4Addr {
650     fn clone(&self) -> Ipv4Addr { *self }
651 }
652
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl PartialEq for Ipv4Addr {
655     fn eq(&self, other: &Ipv4Addr) -> bool {
656         self.inner.s_addr == other.inner.s_addr
657     }
658 }
659
660 #[stable(feature = "ip_cmp", since = "1.16.0")]
661 impl PartialEq<Ipv4Addr> for IpAddr {
662     fn eq(&self, other: &Ipv4Addr) -> bool {
663         match *self {
664             IpAddr::V4(ref v4) => v4 == other,
665             IpAddr::V6(_) => false,
666         }
667     }
668 }
669
670 #[stable(feature = "ip_cmp", since = "1.16.0")]
671 impl PartialEq<IpAddr> for Ipv4Addr {
672     fn eq(&self, other: &IpAddr) -> bool {
673         match *other {
674             IpAddr::V4(ref v4) => self == v4,
675             IpAddr::V6(_) => false,
676         }
677     }
678 }
679
680 #[stable(feature = "rust1", since = "1.0.0")]
681 impl Eq for Ipv4Addr {}
682
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl hash::Hash for Ipv4Addr {
685     fn hash<H: hash::Hasher>(&self, s: &mut H) {
686         self.inner.s_addr.hash(s)
687     }
688 }
689
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl PartialOrd for Ipv4Addr {
692     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
693         Some(self.cmp(other))
694     }
695 }
696
697 #[stable(feature = "ip_cmp", since = "1.16.0")]
698 impl PartialOrd<Ipv4Addr> for IpAddr {
699     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
700         match *self {
701             IpAddr::V4(ref v4) => v4.partial_cmp(other),
702             IpAddr::V6(_) => Some(Ordering::Greater),
703         }
704     }
705 }
706
707 #[stable(feature = "ip_cmp", since = "1.16.0")]
708 impl PartialOrd<IpAddr> for Ipv4Addr {
709     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
710         match *other {
711             IpAddr::V4(ref v4) => self.partial_cmp(v4),
712             IpAddr::V6(_) => Some(Ordering::Less),
713         }
714     }
715 }
716
717 #[stable(feature = "rust1", since = "1.0.0")]
718 impl Ord for Ipv4Addr {
719     fn cmp(&self, other: &Ipv4Addr) -> Ordering {
720         ntoh(self.inner.s_addr).cmp(&ntoh(other.inner.s_addr))
721     }
722 }
723
724 impl AsInner<c::in_addr> for Ipv4Addr {
725     fn as_inner(&self) -> &c::in_addr { &self.inner }
726 }
727 impl FromInner<c::in_addr> for Ipv4Addr {
728     fn from_inner(addr: c::in_addr) -> Ipv4Addr {
729         Ipv4Addr { inner: addr }
730     }
731 }
732
733 #[stable(feature = "ip_u32", since = "1.1.0")]
734 impl From<Ipv4Addr> for u32 {
735     /// It performs the conversion in network order (big-endian).
736     fn from(ip: Ipv4Addr) -> u32 {
737         let ip = ip.octets();
738         ((ip[0] as u32) << 24) + ((ip[1] as u32) << 16) + ((ip[2] as u32) << 8) + (ip[3] as u32)
739     }
740 }
741
742 #[stable(feature = "ip_u32", since = "1.1.0")]
743 impl From<u32> for Ipv4Addr {
744     /// It performs the conversion in network order (big-endian).
745     fn from(ip: u32) -> Ipv4Addr {
746         Ipv4Addr::new((ip >> 24) as u8, (ip >> 16) as u8, (ip >> 8) as u8, ip as u8)
747     }
748 }
749
750 #[stable(feature = "from_slice_v4", since = "1.9.0")]
751 impl From<[u8; 4]> for Ipv4Addr {
752     fn from(octets: [u8; 4]) -> Ipv4Addr {
753         Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
754     }
755 }
756
757 #[stable(feature = "ip_from_slice", since = "1.17.0")]
758 impl From<[u8; 4]> for IpAddr {
759     fn from(octets: [u8; 4]) -> IpAddr {
760         IpAddr::V4(Ipv4Addr::from(octets))
761     }
762 }
763
764 impl Ipv6Addr {
765     /// Creates a new IPv6 address from eight 16-bit segments.
766     ///
767     /// The result will represent the IP address a:b:c:d:e:f:g:h.
768     ///
769     /// # Examples
770     ///
771     /// ```
772     /// use std::net::Ipv6Addr;
773     ///
774     /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
775     /// ```
776     #[stable(feature = "rust1", since = "1.0.0")]
777     pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16,
778                h: u16) -> Ipv6Addr {
779         let mut addr: c::in6_addr = unsafe { mem::zeroed() };
780         addr.s6_addr = [(a >> 8) as u8, a as u8,
781                         (b >> 8) as u8, b as u8,
782                         (c >> 8) as u8, c as u8,
783                         (d >> 8) as u8, d as u8,
784                         (e >> 8) as u8, e as u8,
785                         (f >> 8) as u8, f as u8,
786                         (g >> 8) as u8, g as u8,
787                         (h >> 8) as u8, h as u8];
788         Ipv6Addr { inner: addr }
789     }
790
791     /// Returns the eight 16-bit segments that make up this address.
792     ///
793     /// # Examples
794     ///
795     /// ```
796     /// use std::net::Ipv6Addr;
797     ///
798     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
799     ///            [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
800     /// ```
801     #[stable(feature = "rust1", since = "1.0.0")]
802     pub fn segments(&self) -> [u16; 8] {
803         let arr = &self.inner.s6_addr;
804         [
805             (arr[0] as u16) << 8 | (arr[1] as u16),
806             (arr[2] as u16) << 8 | (arr[3] as u16),
807             (arr[4] as u16) << 8 | (arr[5] as u16),
808             (arr[6] as u16) << 8 | (arr[7] as u16),
809             (arr[8] as u16) << 8 | (arr[9] as u16),
810             (arr[10] as u16) << 8 | (arr[11] as u16),
811             (arr[12] as u16) << 8 | (arr[13] as u16),
812             (arr[14] as u16) << 8 | (arr[15] as u16),
813         ]
814     }
815
816     /// Returns [`true`] for the special 'unspecified' address (::).
817     ///
818     /// This property is defined in [IETF RFC 4291].
819     ///
820     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
821     /// [`true`]: ../../std/primitive.bool.html
822     ///
823     /// # Examples
824     ///
825     /// ```
826     /// use std::net::Ipv6Addr;
827     ///
828     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
829     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
830     /// ```
831     #[stable(since = "1.7.0", feature = "ip_17")]
832     pub fn is_unspecified(&self) -> bool {
833         self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
834     }
835
836     /// Returns [`true`] if this is a loopback address (::1).
837     ///
838     /// This property is defined in [IETF RFC 4291].
839     ///
840     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
841     /// [`true`]: ../../std/primitive.bool.html
842     ///
843     /// # Examples
844     ///
845     /// ```
846     /// use std::net::Ipv6Addr;
847     ///
848     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
849     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
850     /// ```
851     #[stable(since = "1.7.0", feature = "ip_17")]
852     pub fn is_loopback(&self) -> bool {
853         self.segments() == [0, 0, 0, 0, 0, 0, 0, 1]
854     }
855
856     /// Returns [`true`] if the address appears to be globally routable.
857     ///
858     /// The following return [`false`]:
859     ///
860     /// - the loopback address
861     /// - link-local, site-local, and unique local unicast addresses
862     /// - interface-, link-, realm-, admin- and site-local multicast addresses
863     ///
864     /// [`true`]: ../../std/primitive.bool.html
865     /// [`false`]: ../../std/primitive.bool.html
866     ///
867     /// # Examples
868     ///
869     /// ```
870     /// #![feature(ip)]
871     ///
872     /// use std::net::Ipv6Addr;
873     ///
874     /// fn main() {
875     ///     assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), true);
876     ///     assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_global(), false);
877     ///     assert_eq!(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1).is_global(), true);
878     /// }
879     /// ```
880     pub fn is_global(&self) -> bool {
881         match self.multicast_scope() {
882             Some(Ipv6MulticastScope::Global) => true,
883             None => self.is_unicast_global(),
884             _ => false
885         }
886     }
887
888     /// Returns [`true`] if this is a unique local address (fc00::/7).
889     ///
890     /// This property is defined in [IETF RFC 4193].
891     ///
892     /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
893     /// [`true`]: ../../std/primitive.bool.html
894     ///
895     /// # Examples
896     ///
897     /// ```
898     /// #![feature(ip)]
899     ///
900     /// use std::net::Ipv6Addr;
901     ///
902     /// fn main() {
903     ///     assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(),
904     ///                false);
905     ///     assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
906     /// }
907     /// ```
908     pub fn is_unique_local(&self) -> bool {
909         (self.segments()[0] & 0xfe00) == 0xfc00
910     }
911
912     /// Returns [`true`] if the address is unicast and link-local (fe80::/10).
913     ///
914     /// This property is defined in [IETF RFC 4291].
915     ///
916     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
917     /// [`true`]: ../../std/primitive.bool.html
918     ///
919     /// # Examples
920     ///
921     /// ```
922     /// #![feature(ip)]
923     ///
924     /// use std::net::Ipv6Addr;
925     ///
926     /// fn main() {
927     ///     assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_link_local(),
928     ///                false);
929     ///     assert_eq!(Ipv6Addr::new(0xfe8a, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
930     /// }
931     /// ```
932     pub fn is_unicast_link_local(&self) -> bool {
933         (self.segments()[0] & 0xffc0) == 0xfe80
934     }
935
936     /// Returns [`true`] if this is a deprecated unicast site-local address
937     /// (fec0::/10).
938     ///
939     /// [`true`]: ../../std/primitive.bool.html
940     ///
941     /// # Examples
942     ///
943     /// ```
944     /// #![feature(ip)]
945     ///
946     /// use std::net::Ipv6Addr;
947     ///
948     /// fn main() {
949     ///     assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_site_local(),
950     ///                false);
951     ///     assert_eq!(Ipv6Addr::new(0xfec2, 0, 0, 0, 0, 0, 0, 0).is_unicast_site_local(), true);
952     /// }
953     /// ```
954     pub fn is_unicast_site_local(&self) -> bool {
955         (self.segments()[0] & 0xffc0) == 0xfec0
956     }
957
958     /// Returns [`true`] if this is an address reserved for documentation
959     /// (2001:db8::/32).
960     ///
961     /// This property is defined in [IETF RFC 3849].
962     ///
963     /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
964     /// [`true`]: ../../std/primitive.bool.html
965     ///
966     /// # Examples
967     ///
968     /// ```
969     /// #![feature(ip)]
970     ///
971     /// use std::net::Ipv6Addr;
972     ///
973     /// fn main() {
974     ///     assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(),
975     ///                false);
976     ///     assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
977     /// }
978     /// ```
979     pub fn is_documentation(&self) -> bool {
980         (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
981     }
982
983     /// Returns [`true`] if the address is a globally routable unicast address.
984     ///
985     /// The following return false:
986     ///
987     /// - the loopback address
988     /// - the link-local addresses
989     /// - the (deprecated) site-local addresses
990     /// - unique local addresses
991     /// - the unspecified address
992     /// - the address range reserved for documentation
993     ///
994     /// [`true`]: ../../std/primitive.bool.html
995     ///
996     /// # Examples
997     ///
998     /// ```
999     /// #![feature(ip)]
1000     ///
1001     /// use std::net::Ipv6Addr;
1002     ///
1003     /// fn main() {
1004     ///     assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1005     ///     assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(),
1006     ///                true);
1007     /// }
1008     /// ```
1009     pub fn is_unicast_global(&self) -> bool {
1010         !self.is_multicast()
1011             && !self.is_loopback() && !self.is_unicast_link_local()
1012             && !self.is_unicast_site_local() && !self.is_unique_local()
1013             && !self.is_unspecified() && !self.is_documentation()
1014     }
1015
1016     /// Returns the address's multicast scope if the address is multicast.
1017     ///
1018     /// # Examples
1019     ///
1020     /// ```
1021     /// #![feature(ip)]
1022     ///
1023     /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1024     ///
1025     /// fn main() {
1026     ///     assert_eq!(Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1027     ///                              Some(Ipv6MulticastScope::Global));
1028     ///     assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1029     /// }
1030     /// ```
1031     pub fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1032         if self.is_multicast() {
1033             match self.segments()[0] & 0x000f {
1034                 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1035                 2 => Some(Ipv6MulticastScope::LinkLocal),
1036                 3 => Some(Ipv6MulticastScope::RealmLocal),
1037                 4 => Some(Ipv6MulticastScope::AdminLocal),
1038                 5 => Some(Ipv6MulticastScope::SiteLocal),
1039                 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1040                 14 => Some(Ipv6MulticastScope::Global),
1041                 _ => None
1042             }
1043         } else {
1044             None
1045         }
1046     }
1047
1048     /// Returns [`true`] if this is a multicast address (ff00::/8).
1049     ///
1050     /// This property is defined by [IETF RFC 4291].
1051     ///
1052     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1053     /// [`true`]: ../../std/primitive.bool.html
1054     ///
1055     /// # Examples
1056     ///
1057     /// ```
1058     /// use std::net::Ipv6Addr;
1059     ///
1060     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1061     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1062     /// ```
1063     #[stable(since = "1.7.0", feature = "ip_17")]
1064     pub fn is_multicast(&self) -> bool {
1065         (self.segments()[0] & 0xff00) == 0xff00
1066     }
1067
1068     /// Converts this address to an [IPv4 address]. Returns [`None`] if this address is
1069     /// neither IPv4-compatible or IPv4-mapped.
1070     ///
1071     /// ::a.b.c.d and ::ffff:a.b.c.d become a.b.c.d
1072     ///
1073     /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
1074     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1075     ///
1076     /// # Examples
1077     ///
1078     /// ```
1079     /// use std::net::{Ipv4Addr, Ipv6Addr};
1080     ///
1081     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1082     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1083     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1084     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1085     ///            Some(Ipv4Addr::new(0, 0, 0, 1)));
1086     /// ```
1087     #[stable(feature = "rust1", since = "1.0.0")]
1088     pub fn to_ipv4(&self) -> Option<Ipv4Addr> {
1089         match self.segments() {
1090             [0, 0, 0, 0, 0, f, g, h] if f == 0 || f == 0xffff => {
1091                 Some(Ipv4Addr::new((g >> 8) as u8, g as u8,
1092                                    (h >> 8) as u8, h as u8))
1093             },
1094             _ => None
1095         }
1096     }
1097
1098     /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1099     ///
1100     /// ```
1101     /// use std::net::Ipv6Addr;
1102     ///
1103     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1104     ///            [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1105     /// ```
1106     #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1107     pub fn octets(&self) -> [u8; 16] {
1108         self.inner.s6_addr
1109     }
1110 }
1111
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 impl fmt::Display for Ipv6Addr {
1114     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1115         match self.segments() {
1116             // We need special cases for :: and ::1, otherwise they're formatted
1117             // as ::0.0.0.[01]
1118             [0, 0, 0, 0, 0, 0, 0, 0] => write!(fmt, "::"),
1119             [0, 0, 0, 0, 0, 0, 0, 1] => write!(fmt, "::1"),
1120             // Ipv4 Compatible address
1121             [0, 0, 0, 0, 0, 0, g, h] => {
1122                 write!(fmt, "::{}.{}.{}.{}", (g >> 8) as u8, g as u8,
1123                        (h >> 8) as u8, h as u8)
1124             }
1125             // Ipv4-Mapped address
1126             [0, 0, 0, 0, 0, 0xffff, g, h] => {
1127                 write!(fmt, "::ffff:{}.{}.{}.{}", (g >> 8) as u8, g as u8,
1128                        (h >> 8) as u8, h as u8)
1129             },
1130             _ => {
1131                 fn find_zero_slice(segments: &[u16; 8]) -> (usize, usize) {
1132                     let mut longest_span_len = 0;
1133                     let mut longest_span_at = 0;
1134                     let mut cur_span_len = 0;
1135                     let mut cur_span_at = 0;
1136
1137                     for i in 0..8 {
1138                         if segments[i] == 0 {
1139                             if cur_span_len == 0 {
1140                                 cur_span_at = i;
1141                             }
1142
1143                             cur_span_len += 1;
1144
1145                             if cur_span_len > longest_span_len {
1146                                 longest_span_len = cur_span_len;
1147                                 longest_span_at = cur_span_at;
1148                             }
1149                         } else {
1150                             cur_span_len = 0;
1151                             cur_span_at = 0;
1152                         }
1153                     }
1154
1155                     (longest_span_at, longest_span_len)
1156                 }
1157
1158                 let (zeros_at, zeros_len) = find_zero_slice(&self.segments());
1159
1160                 if zeros_len > 1 {
1161                     fn fmt_subslice(segments: &[u16], fmt: &mut fmt::Formatter) -> fmt::Result {
1162                         if !segments.is_empty() {
1163                             write!(fmt, "{:x}", segments[0])?;
1164                             for &seg in &segments[1..] {
1165                                 write!(fmt, ":{:x}", seg)?;
1166                             }
1167                         }
1168                         Ok(())
1169                     }
1170
1171                     fmt_subslice(&self.segments()[..zeros_at], fmt)?;
1172                     fmt.write_str("::")?;
1173                     fmt_subslice(&self.segments()[zeros_at + zeros_len..], fmt)
1174                 } else {
1175                     let &[a, b, c, d, e, f, g, h] = &self.segments();
1176                     write!(fmt, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
1177                            a, b, c, d, e, f, g, h)
1178                 }
1179             }
1180         }
1181     }
1182 }
1183
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl fmt::Debug for Ipv6Addr {
1186     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1187         fmt::Display::fmt(self, fmt)
1188     }
1189 }
1190
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl Clone for Ipv6Addr {
1193     fn clone(&self) -> Ipv6Addr { *self }
1194 }
1195
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 impl PartialEq for Ipv6Addr {
1198     fn eq(&self, other: &Ipv6Addr) -> bool {
1199         self.inner.s6_addr == other.inner.s6_addr
1200     }
1201 }
1202
1203 #[stable(feature = "ip_cmp", since = "1.16.0")]
1204 impl PartialEq<IpAddr> for Ipv6Addr {
1205     fn eq(&self, other: &IpAddr) -> bool {
1206         match *other {
1207             IpAddr::V4(_) => false,
1208             IpAddr::V6(ref v6) => self == v6,
1209         }
1210     }
1211 }
1212
1213 #[stable(feature = "ip_cmp", since = "1.16.0")]
1214 impl PartialEq<Ipv6Addr> for IpAddr {
1215     fn eq(&self, other: &Ipv6Addr) -> bool {
1216         match *self {
1217             IpAddr::V4(_) => false,
1218             IpAddr::V6(ref v6) => v6 == other,
1219         }
1220     }
1221 }
1222
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl Eq for Ipv6Addr {}
1225
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 impl hash::Hash for Ipv6Addr {
1228     fn hash<H: hash::Hasher>(&self, s: &mut H) {
1229         self.inner.s6_addr.hash(s)
1230     }
1231 }
1232
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl PartialOrd for Ipv6Addr {
1235     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1236         Some(self.cmp(other))
1237     }
1238 }
1239
1240 #[stable(feature = "ip_cmp", since = "1.16.0")]
1241 impl PartialOrd<Ipv6Addr> for IpAddr {
1242     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1243         match *self {
1244             IpAddr::V4(_) => Some(Ordering::Less),
1245             IpAddr::V6(ref v6) => v6.partial_cmp(other),
1246         }
1247     }
1248 }
1249
1250 #[stable(feature = "ip_cmp", since = "1.16.0")]
1251 impl PartialOrd<IpAddr> for Ipv6Addr {
1252     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1253         match *other {
1254             IpAddr::V4(_) => Some(Ordering::Greater),
1255             IpAddr::V6(ref v6) => self.partial_cmp(v6),
1256         }
1257     }
1258 }
1259
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 impl Ord for Ipv6Addr {
1262     fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1263         self.segments().cmp(&other.segments())
1264     }
1265 }
1266
1267 impl AsInner<c::in6_addr> for Ipv6Addr {
1268     fn as_inner(&self) -> &c::in6_addr { &self.inner }
1269 }
1270 impl FromInner<c::in6_addr> for Ipv6Addr {
1271     fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1272         Ipv6Addr { inner: addr }
1273     }
1274 }
1275
1276 #[unstable(feature = "i128", issue = "35118")]
1277 impl From<Ipv6Addr> for u128 {
1278     fn from(ip: Ipv6Addr) -> u128 {
1279         let ip = ip.segments();
1280         ((ip[0] as u128) << 112) + ((ip[1] as u128) << 96) + ((ip[2] as u128) << 80) +
1281             ((ip[3] as u128) << 64) + ((ip[4] as u128) << 48) + ((ip[5] as u128) << 32) +
1282             ((ip[6] as u128) << 16) + (ip[7] as u128)
1283     }
1284 }
1285 #[unstable(feature = "i128", issue = "35118")]
1286 impl From<u128> for Ipv6Addr {
1287     fn from(ip: u128) -> Ipv6Addr {
1288         Ipv6Addr::new(
1289             (ip >> 112) as u16, (ip >> 96) as u16, (ip >> 80) as u16,
1290             (ip >> 64) as u16, (ip >> 48) as u16, (ip >> 32) as u16,
1291             (ip >> 16) as u16, ip as u16,
1292         )
1293     }
1294 }
1295
1296 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1297 impl From<[u8; 16]> for Ipv6Addr {
1298     fn from(octets: [u8; 16]) -> Ipv6Addr {
1299         let mut inner: c::in6_addr = unsafe { mem::zeroed() };
1300         inner.s6_addr = octets;
1301         Ipv6Addr::from_inner(inner)
1302     }
1303 }
1304
1305 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
1306 impl From<[u16; 8]> for Ipv6Addr {
1307     fn from(segments: [u16; 8]) -> Ipv6Addr {
1308         let [a, b, c, d, e, f, g, h] = segments;
1309         Ipv6Addr::new(a, b, c, d, e, f, g, h)
1310     }
1311 }
1312
1313
1314 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1315 impl From<[u8; 16]> for IpAddr {
1316     fn from(octets: [u8; 16]) -> IpAddr {
1317         IpAddr::V6(Ipv6Addr::from(octets))
1318     }
1319 }
1320
1321 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1322 impl From<[u16; 8]> for IpAddr {
1323     fn from(segments: [u16; 8]) -> IpAddr {
1324         IpAddr::V6(Ipv6Addr::from(segments))
1325     }
1326 }
1327
1328 // Tests for this module
1329 #[cfg(all(test, not(target_os = "emscripten")))]
1330 mod tests {
1331     use net::*;
1332     use net::Ipv6MulticastScope::*;
1333     use net::test::{tsa, sa6, sa4};
1334
1335     #[test]
1336     fn test_from_str_ipv4() {
1337         assert_eq!(Ok(Ipv4Addr::new(127, 0, 0, 1)), "127.0.0.1".parse());
1338         assert_eq!(Ok(Ipv4Addr::new(255, 255, 255, 255)), "255.255.255.255".parse());
1339         assert_eq!(Ok(Ipv4Addr::new(0, 0, 0, 0)), "0.0.0.0".parse());
1340
1341         // out of range
1342         let none: Option<Ipv4Addr> = "256.0.0.1".parse().ok();
1343         assert_eq!(None, none);
1344         // too short
1345         let none: Option<Ipv4Addr> = "255.0.0".parse().ok();
1346         assert_eq!(None, none);
1347         // too long
1348         let none: Option<Ipv4Addr> = "255.0.0.1.2".parse().ok();
1349         assert_eq!(None, none);
1350         // no number between dots
1351         let none: Option<Ipv4Addr> = "255.0..1".parse().ok();
1352         assert_eq!(None, none);
1353     }
1354
1355     #[test]
1356     fn test_from_str_ipv6() {
1357         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "0:0:0:0:0:0:0:0".parse());
1358         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "0:0:0:0:0:0:0:1".parse());
1359
1360         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "::1".parse());
1361         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "::".parse());
1362
1363         assert_eq!(Ok(Ipv6Addr::new(0x2a02, 0x6b8, 0, 0, 0, 0, 0x11, 0x11)),
1364                 "2a02:6b8::11:11".parse());
1365
1366         // too long group
1367         let none: Option<Ipv6Addr> = "::00000".parse().ok();
1368         assert_eq!(None, none);
1369         // too short
1370         let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7".parse().ok();
1371         assert_eq!(None, none);
1372         // too long
1373         let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7:8:9".parse().ok();
1374         assert_eq!(None, none);
1375         // triple colon
1376         let none: Option<Ipv6Addr> = "1:2:::6:7:8".parse().ok();
1377         assert_eq!(None, none);
1378         // two double colons
1379         let none: Option<Ipv6Addr> = "1:2::6::8".parse().ok();
1380         assert_eq!(None, none);
1381     }
1382
1383     #[test]
1384     fn test_from_str_ipv4_in_ipv6() {
1385         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 545)),
1386                 "::192.0.2.33".parse());
1387         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0xFFFF, 49152, 545)),
1388                 "::FFFF:192.0.2.33".parse());
1389         assert_eq!(Ok(Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 49152, 545)),
1390                 "64:ff9b::192.0.2.33".parse());
1391         assert_eq!(Ok(Ipv6Addr::new(0x2001, 0xdb8, 0x122, 0xc000, 0x2, 0x2100, 49152, 545)),
1392                 "2001:db8:122:c000:2:2100:192.0.2.33".parse());
1393
1394         // colon after v4
1395         let none: Option<Ipv4Addr> = "::127.0.0.1:".parse().ok();
1396         assert_eq!(None, none);
1397         // not enough groups
1398         let none: Option<Ipv6Addr> = "1.2.3.4.5:127.0.0.1".parse().ok();
1399         assert_eq!(None, none);
1400         // too many groups
1401         let none: Option<Ipv6Addr> = "1.2.3.4.5:6:7:127.0.0.1".parse().ok();
1402         assert_eq!(None, none);
1403     }
1404
1405     #[test]
1406     fn test_from_str_socket_addr() {
1407         assert_eq!(Ok(sa4(Ipv4Addr::new(77, 88, 21, 11), 80)),
1408                    "77.88.21.11:80".parse());
1409         assert_eq!(Ok(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80)),
1410                    "77.88.21.11:80".parse());
1411         assert_eq!(Ok(sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53)),
1412                    "[2a02:6b8:0:1::1]:53".parse());
1413         assert_eq!(Ok(SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1,
1414                                                       0, 0, 0, 1), 53, 0, 0)),
1415                    "[2a02:6b8:0:1::1]:53".parse());
1416         assert_eq!(Ok(sa6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7F00, 1), 22)),
1417                    "[::127.0.0.1]:22".parse());
1418         assert_eq!(Ok(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0,
1419                                                       0x7F00, 1), 22, 0, 0)),
1420                    "[::127.0.0.1]:22".parse());
1421
1422         // without port
1423         let none: Option<SocketAddr> = "127.0.0.1".parse().ok();
1424         assert_eq!(None, none);
1425         // without port
1426         let none: Option<SocketAddr> = "127.0.0.1:".parse().ok();
1427         assert_eq!(None, none);
1428         // wrong brackets around v4
1429         let none: Option<SocketAddr> = "[127.0.0.1]:22".parse().ok();
1430         assert_eq!(None, none);
1431         // port out of range
1432         let none: Option<SocketAddr> = "127.0.0.1:123456".parse().ok();
1433         assert_eq!(None, none);
1434     }
1435
1436     #[test]
1437     fn ipv6_addr_to_string() {
1438         // ipv4-mapped address
1439         let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280);
1440         assert_eq!(a1.to_string(), "::ffff:192.0.2.128");
1441
1442         // ipv4-compatible address
1443         let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x280);
1444         assert_eq!(a1.to_string(), "::192.0.2.128");
1445
1446         // v6 address with no zero segments
1447         assert_eq!(Ipv6Addr::new(8, 9, 10, 11, 12, 13, 14, 15).to_string(),
1448                    "8:9:a:b:c:d:e:f");
1449
1450         // reduce a single run of zeros
1451         assert_eq!("ae::ffff:102:304",
1452                    Ipv6Addr::new(0xae, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304).to_string());
1453
1454         // don't reduce just a single zero segment
1455         assert_eq!("1:2:3:4:5:6:0:8",
1456                    Ipv6Addr::new(1, 2, 3, 4, 5, 6, 0, 8).to_string());
1457
1458         // 'any' address
1459         assert_eq!("::", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).to_string());
1460
1461         // loopback address
1462         assert_eq!("::1", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_string());
1463
1464         // ends in zeros
1465         assert_eq!("1::", Ipv6Addr::new(1, 0, 0, 0, 0, 0, 0, 0).to_string());
1466
1467         // two runs of zeros, second one is longer
1468         assert_eq!("1:0:0:4::8", Ipv6Addr::new(1, 0, 0, 4, 0, 0, 0, 8).to_string());
1469
1470         // two runs of zeros, equal length
1471         assert_eq!("1::4:5:0:0:8", Ipv6Addr::new(1, 0, 0, 4, 5, 0, 0, 8).to_string());
1472     }
1473
1474     #[test]
1475     fn ipv4_to_ipv6() {
1476         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678),
1477                    Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_mapped());
1478         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678),
1479                    Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_compatible());
1480     }
1481
1482     #[test]
1483     fn ipv6_to_ipv4() {
1484         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678).to_ipv4(),
1485                    Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
1486         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
1487                    Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
1488         assert_eq!(Ipv6Addr::new(0, 0, 1, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
1489                    None);
1490     }
1491
1492     #[test]
1493     fn ip_properties() {
1494         fn check4(octets: &[u8; 4], unspec: bool, loopback: bool,
1495                   global: bool, multicast: bool, documentation: bool) {
1496             let ip = IpAddr::V4(Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]));
1497             assert_eq!(ip.is_unspecified(), unspec);
1498             assert_eq!(ip.is_loopback(), loopback);
1499             assert_eq!(ip.is_global(), global);
1500             assert_eq!(ip.is_multicast(), multicast);
1501             assert_eq!(ip.is_documentation(), documentation);
1502         }
1503
1504         fn check6(str_addr: &str, unspec: bool, loopback: bool,
1505                   global: bool, u_doc: bool, mcast: bool) {
1506             let ip = IpAddr::V6(str_addr.parse().unwrap());
1507             assert_eq!(ip.is_unspecified(), unspec);
1508             assert_eq!(ip.is_loopback(), loopback);
1509             assert_eq!(ip.is_global(), global);
1510             assert_eq!(ip.is_documentation(), u_doc);
1511             assert_eq!(ip.is_multicast(), mcast);
1512         }
1513
1514         //     address                unspec loopbk global multicast doc
1515         check4(&[0, 0, 0, 0],         true,  false, false,  false,   false);
1516         check4(&[0, 0, 0, 1],         false, false, true,   false,   false);
1517         check4(&[0, 1, 0, 0],         false, false, true,   false,   false);
1518         check4(&[10, 9, 8, 7],        false, false, false,  false,   false);
1519         check4(&[127, 1, 2, 3],       false, true,  false,  false,   false);
1520         check4(&[172, 31, 254, 253],  false, false, false,  false,   false);
1521         check4(&[169, 254, 253, 242], false, false, false,  false,   false);
1522         check4(&[192, 0, 2, 183],     false, false, false,  false,   true);
1523         check4(&[192, 1, 2, 183],     false, false, true,   false,   false);
1524         check4(&[192, 168, 254, 253], false, false, false,  false,   false);
1525         check4(&[198, 51, 100, 0],    false, false, false,  false,   true);
1526         check4(&[203, 0, 113, 0],     false, false, false,  false,   true);
1527         check4(&[203, 2, 113, 0],     false, false, true,   false,   false);
1528         check4(&[224, 0, 0, 0],       false, false, true,   true,    false);
1529         check4(&[239, 255, 255, 255], false, false, true,   true,    false);
1530         check4(&[255, 255, 255, 255], false, false, false,  false,   false);
1531
1532         //     address                            unspec loopbk global doc    mcast
1533         check6("::",                              true,  false, false, false, false);
1534         check6("::1",                             false, true,  false, false, false);
1535         check6("::0.0.0.2",                       false, false, true,  false, false);
1536         check6("1::",                             false, false, true,  false, false);
1537         check6("fc00::",                          false, false, false, false, false);
1538         check6("fdff:ffff::",                     false, false, false, false, false);
1539         check6("fe80:ffff::",                     false, false, false, false, false);
1540         check6("febf:ffff::",                     false, false, false, false, false);
1541         check6("fec0::",                          false, false, false, false, false);
1542         check6("ff01::",                          false, false, false, false, true);
1543         check6("ff02::",                          false, false, false, false, true);
1544         check6("ff03::",                          false, false, false, false, true);
1545         check6("ff04::",                          false, false, false, false, true);
1546         check6("ff05::",                          false, false, false, false, true);
1547         check6("ff08::",                          false, false, false, false, true);
1548         check6("ff0e::",                          false, false, true,  false, true);
1549         check6("2001:db8:85a3::8a2e:370:7334",    false, false, false, true,  false);
1550         check6("102:304:506:708:90a:b0c:d0e:f10", false, false, true,  false, false);
1551     }
1552
1553     #[test]
1554     fn ipv4_properties() {
1555         fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
1556                  private: bool, link_local: bool, global: bool,
1557                  multicast: bool, broadcast: bool, documentation: bool) {
1558             let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
1559             assert_eq!(octets, &ip.octets());
1560
1561             assert_eq!(ip.is_unspecified(), unspec);
1562             assert_eq!(ip.is_loopback(), loopback);
1563             assert_eq!(ip.is_private(), private);
1564             assert_eq!(ip.is_link_local(), link_local);
1565             assert_eq!(ip.is_global(), global);
1566             assert_eq!(ip.is_multicast(), multicast);
1567             assert_eq!(ip.is_broadcast(), broadcast);
1568             assert_eq!(ip.is_documentation(), documentation);
1569         }
1570
1571         //    address                unspec loopbk privt  linloc global multicast brdcast doc
1572         check(&[0, 0, 0, 0],         true,  false, false, false, false,  false,    false,  false);
1573         check(&[0, 0, 0, 1],         false, false, false, false, true,   false,    false,  false);
1574         check(&[0, 1, 0, 0],         false, false, false, false, true,   false,    false,  false);
1575         check(&[10, 9, 8, 7],        false, false, true,  false, false,  false,    false,  false);
1576         check(&[127, 1, 2, 3],       false, true,  false, false, false,  false,    false,  false);
1577         check(&[172, 31, 254, 253],  false, false, true,  false, false,  false,    false,  false);
1578         check(&[169, 254, 253, 242], false, false, false, true,  false,  false,    false,  false);
1579         check(&[192, 0, 2, 183],     false, false, false, false, false,  false,    false,  true);
1580         check(&[192, 1, 2, 183],     false, false, false, false, true,   false,    false,  false);
1581         check(&[192, 168, 254, 253], false, false, true,  false, false,  false,    false,  false);
1582         check(&[198, 51, 100, 0],    false, false, false, false, false,  false,    false,  true);
1583         check(&[203, 0, 113, 0],     false, false, false, false, false,  false,    false,  true);
1584         check(&[203, 2, 113, 0],     false, false, false, false, true,   false,    false,  false);
1585         check(&[224, 0, 0, 0],       false, false, false, false, true,   true,     false,  false);
1586         check(&[239, 255, 255, 255], false, false, false, false, true,   true,     false,  false);
1587         check(&[255, 255, 255, 255], false, false, false, false, false,  false,    true,   false);
1588     }
1589
1590     #[test]
1591     fn ipv6_properties() {
1592         fn check(str_addr: &str, octets: &[u8; 16], unspec: bool, loopback: bool,
1593                  unique_local: bool, global: bool,
1594                  u_link_local: bool, u_site_local: bool, u_global: bool, u_doc: bool,
1595                  m_scope: Option<Ipv6MulticastScope>) {
1596             let ip: Ipv6Addr = str_addr.parse().unwrap();
1597             assert_eq!(str_addr, ip.to_string());
1598             assert_eq!(&ip.octets(), octets);
1599             assert_eq!(Ipv6Addr::from(*octets), ip);
1600
1601             assert_eq!(ip.is_unspecified(), unspec);
1602             assert_eq!(ip.is_loopback(), loopback);
1603             assert_eq!(ip.is_unique_local(), unique_local);
1604             assert_eq!(ip.is_global(), global);
1605             assert_eq!(ip.is_unicast_link_local(), u_link_local);
1606             assert_eq!(ip.is_unicast_site_local(), u_site_local);
1607             assert_eq!(ip.is_unicast_global(), u_global);
1608             assert_eq!(ip.is_documentation(), u_doc);
1609             assert_eq!(ip.multicast_scope(), m_scope);
1610             assert_eq!(ip.is_multicast(), m_scope.is_some());
1611         }
1612
1613         //    unspec loopbk uniqlo global unill  unisl  uniglo doc    mscope
1614         check("::", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1615               true,  false, false, false, false, false, false, false, None);
1616         check("::1", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
1617               false, true,  false, false, false, false, false, false, None);
1618         check("::0.0.0.2", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2],
1619               false, false, false, true,  false, false, true,  false, None);
1620         check("1::", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1621               false, false, false, true,  false, false, true,  false, None);
1622         check("fc00::", &[0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1623               false, false, true,  false, false, false, false, false, None);
1624         check("fdff:ffff::", &[0xfd, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1625               false, false, true,  false, false, false, false, false, None);
1626         check("fe80:ffff::", &[0xfe, 0x80, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1627               false, false, false, false, true,  false, false, false, None);
1628         check("febf:ffff::", &[0xfe, 0xbf, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1629               false, false, false, false, true,  false, false, false, None);
1630         check("fec0::", &[0xfe, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1631               false, false, false, false, false, true,  false, false, None);
1632         check("ff01::", &[0xff, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1633               false, false, false, false, false, false, false, false, Some(InterfaceLocal));
1634         check("ff02::", &[0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1635               false, false, false, false, false, false, false, false, Some(LinkLocal));
1636         check("ff03::", &[0xff, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1637               false, false, false, false, false, false, false, false, Some(RealmLocal));
1638         check("ff04::", &[0xff, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1639               false, false, false, false, false, false, false, false, Some(AdminLocal));
1640         check("ff05::", &[0xff, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1641               false, false, false, false, false, false, false, false, Some(SiteLocal));
1642         check("ff08::", &[0xff, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1643               false, false, false, false, false, false, false, false, Some(OrganizationLocal));
1644         check("ff0e::", &[0xff, 0xe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1645               false, false, false, true,  false, false, false, false, Some(Global));
1646         check("2001:db8:85a3::8a2e:370:7334",
1647               &[0x20, 1, 0xd, 0xb8, 0x85, 0xa3, 0, 0, 0, 0, 0x8a, 0x2e, 3, 0x70, 0x73, 0x34],
1648               false, false, false, false, false, false, false, true, None);
1649         check("102:304:506:708:90a:b0c:d0e:f10",
1650               &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
1651               false, false, false, true,  false, false, true,  false, None);
1652     }
1653
1654     #[test]
1655     fn to_socket_addr_socketaddr() {
1656         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 12345);
1657         assert_eq!(Ok(vec![a]), tsa(a));
1658     }
1659
1660     #[test]
1661     fn test_ipv4_to_int() {
1662         let a = Ipv4Addr::new(0x11, 0x22, 0x33, 0x44);
1663         assert_eq!(u32::from(a), 0x11223344);
1664     }
1665
1666     #[test]
1667     fn test_int_to_ipv4() {
1668         let a = Ipv4Addr::new(0x11, 0x22, 0x33, 0x44);
1669         assert_eq!(Ipv4Addr::from(0x11223344), a);
1670     }
1671
1672     #[test]
1673     fn test_ipv6_to_int() {
1674         let a = Ipv6Addr::new(0x1122, 0x3344, 0x5566, 0x7788, 0x99aa, 0xbbcc, 0xddee, 0xff11);
1675         assert_eq!(u128::from(a), 0x112233445566778899aabbccddeeff11u128);
1676     }
1677
1678     #[test]
1679     fn test_int_to_ipv6() {
1680         let a = Ipv6Addr::new(0x1122, 0x3344, 0x5566, 0x7788, 0x99aa, 0xbbcc, 0xddee, 0xff11);
1681         assert_eq!(Ipv6Addr::from(0x112233445566778899aabbccddeeff11u128), a);
1682     }
1683
1684     #[test]
1685     fn ipv4_from_octets() {
1686         assert_eq!(Ipv4Addr::from([127, 0, 0, 1]), Ipv4Addr::new(127, 0, 0, 1))
1687     }
1688
1689     #[test]
1690     fn ipv6_from_segments() {
1691         let from_u16s = Ipv6Addr::from([0x0011, 0x2233, 0x4455, 0x6677,
1692                                         0x8899, 0xaabb, 0xccdd, 0xeeff]);
1693         let new = Ipv6Addr::new(0x0011, 0x2233, 0x4455, 0x6677,
1694                                 0x8899, 0xaabb, 0xccdd, 0xeeff);
1695         assert_eq!(new, from_u16s);
1696     }
1697
1698     #[test]
1699     fn ipv6_from_octets() {
1700         let from_u16s = Ipv6Addr::from([0x0011, 0x2233, 0x4455, 0x6677,
1701                                         0x8899, 0xaabb, 0xccdd, 0xeeff]);
1702         let from_u8s = Ipv6Addr::from([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
1703                                        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]);
1704         assert_eq!(from_u16s, from_u8s);
1705     }
1706
1707     #[test]
1708     fn cmp() {
1709         let v41 = Ipv4Addr::new(100, 64, 3, 3);
1710         let v42 = Ipv4Addr::new(192, 0, 2, 2);
1711         let v61 = "2001:db8:f00::1002".parse::<Ipv6Addr>().unwrap();
1712         let v62 = "2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap();
1713         assert!(v41 < v42);
1714         assert!(v61 < v62);
1715
1716         assert_eq!(v41, IpAddr::V4(v41));
1717         assert_eq!(v61, IpAddr::V6(v61));
1718         assert!(v41 != IpAddr::V4(v42));
1719         assert!(v61 != IpAddr::V6(v62));
1720
1721         assert!(v41 < IpAddr::V4(v42));
1722         assert!(v61 < IpAddr::V6(v62));
1723         assert!(IpAddr::V4(v41) < v42);
1724         assert!(IpAddr::V6(v61) < v62);
1725
1726         assert!(v41 < IpAddr::V6(v61));
1727         assert!(IpAddr::V4(v41) < v61);
1728     }
1729
1730     #[test]
1731     fn is_v4() {
1732         let ip = IpAddr::V4(Ipv4Addr::new(100, 64, 3, 3));
1733         assert!(ip.is_ipv4());
1734         assert!(!ip.is_ipv6());
1735     }
1736
1737     #[test]
1738     fn is_v6() {
1739         let ip = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678));
1740         assert!(!ip.is_ipv4());
1741         assert!(ip.is_ipv6());
1742     }
1743 }