]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/ip.rs
Auto merge of #35856 - phimuemue:master, r=brson
[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 an IPv4 or IPv6 address.
25 #[stable(feature = "ip_addr", since = "1.7.0")]
26 #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
27 pub enum IpAddr {
28     /// Representation of an IPv4 address.
29     #[stable(feature = "ip_addr", since = "1.7.0")]
30     V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
31     /// Representation of an IPv6 address.
32     #[stable(feature = "ip_addr", since = "1.7.0")]
33     V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
34 }
35
36 /// Representation of an IPv4 address.
37 #[derive(Copy)]
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub struct Ipv4Addr {
40     inner: c::in_addr,
41 }
42
43 /// Representation of an IPv6 address.
44 #[derive(Copy)]
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct Ipv6Addr {
47     inner: c::in6_addr,
48 }
49
50 #[allow(missing_docs)]
51 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
52 pub enum Ipv6MulticastScope {
53     InterfaceLocal,
54     LinkLocal,
55     RealmLocal,
56     AdminLocal,
57     SiteLocal,
58     OrganizationLocal,
59     Global
60 }
61
62 impl IpAddr {
63     /// Returns true for the special 'unspecified' address ([IPv4], [IPv6]).
64     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_unspecified
65     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_unspecified
66     #[stable(feature = "ip_shared", since = "1.12.0")]
67     pub fn is_unspecified(&self) -> bool {
68         match *self {
69             IpAddr::V4(ref a) => a.is_unspecified(),
70             IpAddr::V6(ref a) => a.is_unspecified(),
71         }
72     }
73
74     /// Returns true if this is a loopback address ([IPv4], [IPv6]).
75     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_loopback
76     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_loopback
77     #[stable(feature = "ip_shared", since = "1.12.0")]
78     pub fn is_loopback(&self) -> bool {
79         match *self {
80             IpAddr::V4(ref a) => a.is_loopback(),
81             IpAddr::V6(ref a) => a.is_loopback(),
82         }
83     }
84
85     /// Returns true if the address appears to be globally routable ([IPv4], [IPv6]).
86     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_global
87     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_global
88     pub fn is_global(&self) -> bool {
89         match *self {
90             IpAddr::V4(ref a) => a.is_global(),
91             IpAddr::V6(ref a) => a.is_global(),
92         }
93     }
94
95     /// Returns true if this is a multicast address ([IPv4], [IPv6]).
96     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_multicast
97     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_multicast
98     #[stable(feature = "ip_shared", since = "1.12.0")]
99     pub fn is_multicast(&self) -> bool {
100         match *self {
101             IpAddr::V4(ref a) => a.is_multicast(),
102             IpAddr::V6(ref a) => a.is_multicast(),
103         }
104     }
105
106     /// Returns true if this address is in a range designated for documentation ([IPv4], [IPv6]).
107     /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_documentation
108     /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_documentation
109     pub fn is_documentation(&self) -> bool {
110         match *self {
111             IpAddr::V4(ref a) => a.is_documentation(),
112             IpAddr::V6(ref a) => a.is_documentation(),
113         }
114     }
115 }
116
117 impl Ipv4Addr {
118     /// Creates a new IPv4 address from four eight-bit octets.
119     ///
120     /// The result will represent the IP address `a`.`b`.`c`.`d`.
121     #[stable(feature = "rust1", since = "1.0.0")]
122     pub fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
123         Ipv4Addr {
124             inner: c::in_addr {
125                 s_addr: hton(((a as u32) << 24) |
126                              ((b as u32) << 16) |
127                              ((c as u32) <<  8) |
128                               (d as u32)),
129             }
130         }
131     }
132
133     /// Returns the four eight-bit integers that make up this address.
134     #[stable(feature = "rust1", since = "1.0.0")]
135     pub fn octets(&self) -> [u8; 4] {
136         let bits = ntoh(self.inner.s_addr);
137         [(bits >> 24) as u8, (bits >> 16) as u8, (bits >> 8) as u8, bits as u8]
138     }
139
140     /// Returns true for the special 'unspecified' address (0.0.0.0).
141     ///
142     /// This property is defined in _UNIX Network Programming, Second Edition_,
143     /// W. Richard Stevens, p. 891; see also [ip7]
144     /// [ip7][http://man7.org/linux/man-pages/man7/ip.7.html]
145     #[stable(feature = "ip_shared", since = "1.12.0")]
146     pub fn is_unspecified(&self) -> bool {
147         self.inner.s_addr == 0
148     }
149
150     /// Returns true if this is a loopback address (127.0.0.0/8).
151     ///
152     /// This property is defined by [RFC 1122].
153     /// [RFC 1122]: https://tools.ietf.org/html/rfc1122
154     #[stable(since = "1.7.0", feature = "ip_17")]
155     pub fn is_loopback(&self) -> bool {
156         self.octets()[0] == 127
157     }
158
159     /// Returns true if this is a private address.
160     ///
161     /// The private address ranges are defined in [RFC 1918] and include:
162     /// [RFC 1918]: https://tools.ietf.org/html/rfc1918
163     ///
164     ///  - 10.0.0.0/8
165     ///  - 172.16.0.0/12
166     ///  - 192.168.0.0/16
167     #[stable(since = "1.7.0", feature = "ip_17")]
168     pub fn is_private(&self) -> bool {
169         match (self.octets()[0], self.octets()[1]) {
170             (10, _) => true,
171             (172, b) if b >= 16 && b <= 31 => true,
172             (192, 168) => true,
173             _ => false
174         }
175     }
176
177     /// Returns true if the address is link-local (169.254.0.0/16).
178     ///
179     /// This property is defined by [RFC 3927].
180     /// [RFC 3927]: https://tools.ietf.org/html/rfc3927
181     #[stable(since = "1.7.0", feature = "ip_17")]
182     pub fn is_link_local(&self) -> bool {
183         self.octets()[0] == 169 && self.octets()[1] == 254
184     }
185
186     /// Returns true if the address appears to be globally routable.
187     /// See [iana-ipv4-special-registry][ipv4-sr].
188     /// [ipv4-sr]: http://goo.gl/RaZ7lg
189     ///
190     /// The following return false:
191     ///
192     /// - private address (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16)
193     /// - the loopback address (127.0.0.0/8)
194     /// - the link-local address (169.254.0.0/16)
195     /// - the broadcast address (255.255.255.255/32)
196     /// - test addresses used for documentation (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24)
197     /// - the unspecified address (0.0.0.0)
198     pub fn is_global(&self) -> bool {
199         !self.is_private() && !self.is_loopback() && !self.is_link_local() &&
200         !self.is_broadcast() && !self.is_documentation() && !self.is_unspecified()
201     }
202
203     /// Returns true if this is a multicast address (224.0.0.0/4).
204     ///
205     /// Multicast addresses have a most significant octet between 224 and 239,
206     /// and is defined by [RFC 5771].
207     /// [RFC 5771]: https://tools.ietf.org/html/rfc5771
208     #[stable(since = "1.7.0", feature = "ip_17")]
209     pub fn is_multicast(&self) -> bool {
210         self.octets()[0] >= 224 && self.octets()[0] <= 239
211     }
212
213     /// Returns true if this is a broadcast address (255.255.255.255).
214     ///
215     /// A broadcast address has all octets set to 255 as defined in [RFC 919].
216     /// [RFC 919]: https://tools.ietf.org/html/rfc919
217     #[stable(since = "1.7.0", feature = "ip_17")]
218     pub fn is_broadcast(&self) -> bool {
219         self.octets()[0] == 255 && self.octets()[1] == 255 &&
220         self.octets()[2] == 255 && self.octets()[3] == 255
221     }
222
223     /// Returns true if this address is in a range designated for documentation.
224     ///
225     /// This is defined in [RFC 5737]:
226     /// [RFC 5737]: https://tools.ietf.org/html/rfc5737
227     ///
228     /// - 192.0.2.0/24 (TEST-NET-1)
229     /// - 198.51.100.0/24 (TEST-NET-2)
230     /// - 203.0.113.0/24 (TEST-NET-3)
231     #[stable(since = "1.7.0", feature = "ip_17")]
232     pub fn is_documentation(&self) -> bool {
233         match(self.octets()[0], self.octets()[1], self.octets()[2], self.octets()[3]) {
234             (192, 0, 2, _) => true,
235             (198, 51, 100, _) => true,
236             (203, 0, 113, _) => true,
237             _ => false
238         }
239     }
240
241     /// Converts this address to an IPv4-compatible IPv6 address.
242     ///
243     /// a.b.c.d becomes ::a.b.c.d
244     #[stable(feature = "rust1", since = "1.0.0")]
245     pub fn to_ipv6_compatible(&self) -> Ipv6Addr {
246         Ipv6Addr::new(0, 0, 0, 0, 0, 0,
247                       ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
248                       ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
249     }
250
251     /// Converts this address to an IPv4-mapped IPv6 address.
252     ///
253     /// a.b.c.d becomes ::ffff:a.b.c.d
254     #[stable(feature = "rust1", since = "1.0.0")]
255     pub fn to_ipv6_mapped(&self) -> Ipv6Addr {
256         Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff,
257                       ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
258                       ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
259     }
260 }
261
262 #[stable(feature = "rust1", since = "1.0.0")]
263 #[allow(deprecated)]
264 impl fmt::Display for IpAddr {
265     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
266         match *self {
267             IpAddr::V4(ref a) => a.fmt(fmt),
268             IpAddr::V6(ref a) => a.fmt(fmt),
269         }
270     }
271 }
272
273 #[stable(feature = "rust1", since = "1.0.0")]
274 impl fmt::Display for Ipv4Addr {
275     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
276         let octets = self.octets();
277         write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
278     }
279 }
280
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl fmt::Debug for Ipv4Addr {
283     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
284         fmt::Display::fmt(self, fmt)
285     }
286 }
287
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl Clone for Ipv4Addr {
290     fn clone(&self) -> Ipv4Addr { *self }
291 }
292
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl PartialEq for Ipv4Addr {
295     fn eq(&self, other: &Ipv4Addr) -> bool {
296         self.inner.s_addr == other.inner.s_addr
297     }
298 }
299
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl Eq for Ipv4Addr {}
302
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl hash::Hash for Ipv4Addr {
305     fn hash<H: hash::Hasher>(&self, s: &mut H) {
306         self.inner.s_addr.hash(s)
307     }
308 }
309
310 #[stable(feature = "rust1", since = "1.0.0")]
311 impl PartialOrd for Ipv4Addr {
312     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
313         Some(self.cmp(other))
314     }
315 }
316
317 #[stable(feature = "rust1", since = "1.0.0")]
318 impl Ord for Ipv4Addr {
319     fn cmp(&self, other: &Ipv4Addr) -> Ordering {
320         ntoh(self.inner.s_addr).cmp(&ntoh(other.inner.s_addr))
321     }
322 }
323
324 impl AsInner<c::in_addr> for Ipv4Addr {
325     fn as_inner(&self) -> &c::in_addr { &self.inner }
326 }
327 impl FromInner<c::in_addr> for Ipv4Addr {
328     fn from_inner(addr: c::in_addr) -> Ipv4Addr {
329         Ipv4Addr { inner: addr }
330     }
331 }
332
333 #[stable(feature = "ip_u32", since = "1.1.0")]
334 impl From<Ipv4Addr> for u32 {
335     fn from(ip: Ipv4Addr) -> u32 {
336         let ip = ip.octets();
337         ((ip[0] as u32) << 24) + ((ip[1] as u32) << 16) + ((ip[2] as u32) << 8) + (ip[3] as u32)
338     }
339 }
340
341 #[stable(feature = "ip_u32", since = "1.1.0")]
342 impl From<u32> for Ipv4Addr {
343     fn from(ip: u32) -> Ipv4Addr {
344         Ipv4Addr::new((ip >> 24) as u8, (ip >> 16) as u8, (ip >> 8) as u8, ip as u8)
345     }
346 }
347
348 #[stable(feature = "from_slice_v4", since = "1.9.0")]
349 impl From<[u8; 4]> for Ipv4Addr {
350     fn from(octets: [u8; 4]) -> Ipv4Addr {
351         Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
352     }
353 }
354
355 impl Ipv6Addr {
356     /// Creates a new IPv6 address from eight 16-bit segments.
357     ///
358     /// The result will represent the IP address a:b:c:d:e:f:g:h.
359     #[stable(feature = "rust1", since = "1.0.0")]
360     pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16,
361                h: u16) -> Ipv6Addr {
362         let mut addr: c::in6_addr = unsafe { mem::zeroed() };
363         addr.s6_addr = [(a >> 8) as u8, a as u8,
364                         (b >> 8) as u8, b as u8,
365                         (c >> 8) as u8, c as u8,
366                         (d >> 8) as u8, d as u8,
367                         (e >> 8) as u8, e as u8,
368                         (f >> 8) as u8, f as u8,
369                         (g >> 8) as u8, g as u8,
370                         (h >> 8) as u8, h as u8];
371         Ipv6Addr { inner: addr }
372     }
373
374     /// Returns the eight 16-bit segments that make up this address.
375     #[stable(feature = "rust1", since = "1.0.0")]
376     pub fn segments(&self) -> [u16; 8] {
377         let arr = &self.inner.s6_addr;
378         [
379             (arr[0] as u16) << 8 | (arr[1] as u16),
380             (arr[2] as u16) << 8 | (arr[3] as u16),
381             (arr[4] as u16) << 8 | (arr[5] as u16),
382             (arr[6] as u16) << 8 | (arr[7] as u16),
383             (arr[8] as u16) << 8 | (arr[9] as u16),
384             (arr[10] as u16) << 8 | (arr[11] as u16),
385             (arr[12] as u16) << 8 | (arr[13] as u16),
386             (arr[14] as u16) << 8 | (arr[15] as u16),
387         ]
388     }
389
390     /// Returns true for the special 'unspecified' address (::).
391     ///
392     /// This property is defined in [RFC 4291].
393     /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
394     #[stable(since = "1.7.0", feature = "ip_17")]
395     pub fn is_unspecified(&self) -> bool {
396         self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
397     }
398
399     /// Returns true if this is a loopback address (::1).
400     ///
401     /// This property is defined in [RFC 4291].
402     /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
403     #[stable(since = "1.7.0", feature = "ip_17")]
404     pub fn is_loopback(&self) -> bool {
405         self.segments() == [0, 0, 0, 0, 0, 0, 0, 1]
406     }
407
408     /// Returns true if the address appears to be globally routable.
409     ///
410     /// The following return false:
411     ///
412     /// - the loopback address
413     /// - link-local, site-local, and unique local unicast addresses
414     /// - interface-, link-, realm-, admin- and site-local multicast addresses
415     pub fn is_global(&self) -> bool {
416         match self.multicast_scope() {
417             Some(Ipv6MulticastScope::Global) => true,
418             None => self.is_unicast_global(),
419             _ => false
420         }
421     }
422
423     /// Returns true if this is a unique local address (fc00::/7).
424     ///
425     /// This property is defined in [RFC 4193].
426     /// [RFC 4193]: https://tools.ietf.org/html/rfc4193
427     pub fn is_unique_local(&self) -> bool {
428         (self.segments()[0] & 0xfe00) == 0xfc00
429     }
430
431     /// Returns true if the address is unicast and link-local (fe80::/10).
432     ///
433     /// This property is defined in [RFC 4291].
434     /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
435     pub fn is_unicast_link_local(&self) -> bool {
436         (self.segments()[0] & 0xffc0) == 0xfe80
437     }
438
439     /// Returns true if this is a deprecated unicast site-local address
440     /// (fec0::/10).
441     pub fn is_unicast_site_local(&self) -> bool {
442         (self.segments()[0] & 0xffc0) == 0xfec0
443     }
444
445     /// Returns true if this is an address reserved for documentation
446     /// (2001:db8::/32).
447     ///
448     /// This property is defined in [RFC 3849].
449     /// [RFC 3849]: https://tools.ietf.org/html/rfc3849
450     pub fn is_documentation(&self) -> bool {
451         (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
452     }
453
454     /// Returns true if the address is a globally routable unicast address.
455     ///
456     /// The following return false:
457     ///
458     /// - the loopback address
459     /// - the link-local addresses
460     /// - the (deprecated) site-local addresses
461     /// - unique local addresses
462     /// - the unspecified address
463     /// - the address range reserved for documentation
464     pub fn is_unicast_global(&self) -> bool {
465         !self.is_multicast()
466             && !self.is_loopback() && !self.is_unicast_link_local()
467             && !self.is_unicast_site_local() && !self.is_unique_local()
468             && !self.is_unspecified() && !self.is_documentation()
469     }
470
471     /// Returns the address's multicast scope if the address is multicast.
472     pub fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
473         if self.is_multicast() {
474             match self.segments()[0] & 0x000f {
475                 1 => Some(Ipv6MulticastScope::InterfaceLocal),
476                 2 => Some(Ipv6MulticastScope::LinkLocal),
477                 3 => Some(Ipv6MulticastScope::RealmLocal),
478                 4 => Some(Ipv6MulticastScope::AdminLocal),
479                 5 => Some(Ipv6MulticastScope::SiteLocal),
480                 8 => Some(Ipv6MulticastScope::OrganizationLocal),
481                 14 => Some(Ipv6MulticastScope::Global),
482                 _ => None
483             }
484         } else {
485             None
486         }
487     }
488
489     /// Returns true if this is a multicast address (ff00::/8).
490     ///
491     /// This property is defined by [RFC 4291].
492     /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
493     #[stable(since = "1.7.0", feature = "ip_17")]
494     pub fn is_multicast(&self) -> bool {
495         (self.segments()[0] & 0xff00) == 0xff00
496     }
497
498     /// Converts this address to an IPv4 address. Returns None if this address is
499     /// neither IPv4-compatible or IPv4-mapped.
500     ///
501     /// ::a.b.c.d and ::ffff:a.b.c.d become a.b.c.d
502     #[stable(feature = "rust1", since = "1.0.0")]
503     pub fn to_ipv4(&self) -> Option<Ipv4Addr> {
504         match self.segments() {
505             [0, 0, 0, 0, 0, f, g, h] if f == 0 || f == 0xffff => {
506                 Some(Ipv4Addr::new((g >> 8) as u8, g as u8,
507                                    (h >> 8) as u8, h as u8))
508             },
509             _ => None
510         }
511     }
512
513     /// Returns the sixteen eight-bit integers the IPv6 address consists of.
514     #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
515     pub fn octets(&self) -> [u8; 16] {
516         self.inner.s6_addr
517     }
518 }
519
520 #[stable(feature = "rust1", since = "1.0.0")]
521 impl fmt::Display for Ipv6Addr {
522     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
523         match self.segments() {
524             // We need special cases for :: and ::1, otherwise they're formatted
525             // as ::0.0.0.[01]
526             [0, 0, 0, 0, 0, 0, 0, 0] => write!(fmt, "::"),
527             [0, 0, 0, 0, 0, 0, 0, 1] => write!(fmt, "::1"),
528             // Ipv4 Compatible address
529             [0, 0, 0, 0, 0, 0, g, h] => {
530                 write!(fmt, "::{}.{}.{}.{}", (g >> 8) as u8, g as u8,
531                        (h >> 8) as u8, h as u8)
532             }
533             // Ipv4-Mapped address
534             [0, 0, 0, 0, 0, 0xffff, g, h] => {
535                 write!(fmt, "::ffff:{}.{}.{}.{}", (g >> 8) as u8, g as u8,
536                        (h >> 8) as u8, h as u8)
537             },
538             _ => {
539                 fn find_zero_slice(segments: &[u16; 8]) -> (usize, usize) {
540                     let mut longest_span_len = 0;
541                     let mut longest_span_at = 0;
542                     let mut cur_span_len = 0;
543                     let mut cur_span_at = 0;
544
545                     for i in 0..8 {
546                         if segments[i] == 0 {
547                             if cur_span_len == 0 {
548                                 cur_span_at = i;
549                             }
550
551                             cur_span_len += 1;
552
553                             if cur_span_len > longest_span_len {
554                                 longest_span_len = cur_span_len;
555                                 longest_span_at = cur_span_at;
556                             }
557                         } else {
558                             cur_span_len = 0;
559                             cur_span_at = 0;
560                         }
561                     }
562
563                     (longest_span_at, longest_span_len)
564                 }
565
566                 let (zeros_at, zeros_len) = find_zero_slice(&self.segments());
567
568                 if zeros_len > 1 {
569                     fn fmt_subslice(segments: &[u16], fmt: &mut fmt::Formatter) -> fmt::Result {
570                         if !segments.is_empty() {
571                             write!(fmt, "{:x}", segments[0])?;
572                             for &seg in &segments[1..] {
573                                 write!(fmt, ":{:x}", seg)?;
574                             }
575                         }
576                         Ok(())
577                     }
578
579                     fmt_subslice(&self.segments()[..zeros_at], fmt)?;
580                     fmt.write_str("::")?;
581                     fmt_subslice(&self.segments()[zeros_at + zeros_len..], fmt)
582                 } else {
583                     let &[a, b, c, d, e, f, g, h] = &self.segments();
584                     write!(fmt, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
585                            a, b, c, d, e, f, g, h)
586                 }
587             }
588         }
589     }
590 }
591
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl fmt::Debug for Ipv6Addr {
594     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
595         fmt::Display::fmt(self, fmt)
596     }
597 }
598
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl Clone for Ipv6Addr {
601     fn clone(&self) -> Ipv6Addr { *self }
602 }
603
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl PartialEq for Ipv6Addr {
606     fn eq(&self, other: &Ipv6Addr) -> bool {
607         self.inner.s6_addr == other.inner.s6_addr
608     }
609 }
610
611 #[stable(feature = "rust1", since = "1.0.0")]
612 impl Eq for Ipv6Addr {}
613
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl hash::Hash for Ipv6Addr {
616     fn hash<H: hash::Hasher>(&self, s: &mut H) {
617         self.inner.s6_addr.hash(s)
618     }
619 }
620
621 #[stable(feature = "rust1", since = "1.0.0")]
622 impl PartialOrd for Ipv6Addr {
623     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
624         Some(self.cmp(other))
625     }
626 }
627
628 #[stable(feature = "rust1", since = "1.0.0")]
629 impl Ord for Ipv6Addr {
630     fn cmp(&self, other: &Ipv6Addr) -> Ordering {
631         self.segments().cmp(&other.segments())
632     }
633 }
634
635 impl AsInner<c::in6_addr> for Ipv6Addr {
636     fn as_inner(&self) -> &c::in6_addr { &self.inner }
637 }
638 impl FromInner<c::in6_addr> for Ipv6Addr {
639     fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
640         Ipv6Addr { inner: addr }
641     }
642 }
643
644 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
645 impl From<[u8; 16]> for Ipv6Addr {
646     fn from(octets: [u8; 16]) -> Ipv6Addr {
647         let mut inner: c::in6_addr = unsafe { mem::zeroed() };
648         inner.s6_addr = octets;
649         Ipv6Addr::from_inner(inner)
650     }
651 }
652
653 // Tests for this module
654 #[cfg(test)]
655 mod tests {
656     use net::*;
657     use net::Ipv6MulticastScope::*;
658     use net::test::{tsa, sa6, sa4};
659
660     #[test]
661     fn test_from_str_ipv4() {
662         assert_eq!(Ok(Ipv4Addr::new(127, 0, 0, 1)), "127.0.0.1".parse());
663         assert_eq!(Ok(Ipv4Addr::new(255, 255, 255, 255)), "255.255.255.255".parse());
664         assert_eq!(Ok(Ipv4Addr::new(0, 0, 0, 0)), "0.0.0.0".parse());
665
666         // out of range
667         let none: Option<Ipv4Addr> = "256.0.0.1".parse().ok();
668         assert_eq!(None, none);
669         // too short
670         let none: Option<Ipv4Addr> = "255.0.0".parse().ok();
671         assert_eq!(None, none);
672         // too long
673         let none: Option<Ipv4Addr> = "255.0.0.1.2".parse().ok();
674         assert_eq!(None, none);
675         // no number between dots
676         let none: Option<Ipv4Addr> = "255.0..1".parse().ok();
677         assert_eq!(None, none);
678     }
679
680     #[test]
681     fn test_from_str_ipv6() {
682         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "0:0:0:0:0:0:0:0".parse());
683         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "0:0:0:0:0:0:0:1".parse());
684
685         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "::1".parse());
686         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "::".parse());
687
688         assert_eq!(Ok(Ipv6Addr::new(0x2a02, 0x6b8, 0, 0, 0, 0, 0x11, 0x11)),
689                 "2a02:6b8::11:11".parse());
690
691         // too long group
692         let none: Option<Ipv6Addr> = "::00000".parse().ok();
693         assert_eq!(None, none);
694         // too short
695         let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7".parse().ok();
696         assert_eq!(None, none);
697         // too long
698         let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7:8:9".parse().ok();
699         assert_eq!(None, none);
700         // triple colon
701         let none: Option<Ipv6Addr> = "1:2:::6:7:8".parse().ok();
702         assert_eq!(None, none);
703         // two double colons
704         let none: Option<Ipv6Addr> = "1:2::6::8".parse().ok();
705         assert_eq!(None, none);
706     }
707
708     #[test]
709     fn test_from_str_ipv4_in_ipv6() {
710         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 545)),
711                 "::192.0.2.33".parse());
712         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0xFFFF, 49152, 545)),
713                 "::FFFF:192.0.2.33".parse());
714         assert_eq!(Ok(Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 49152, 545)),
715                 "64:ff9b::192.0.2.33".parse());
716         assert_eq!(Ok(Ipv6Addr::new(0x2001, 0xdb8, 0x122, 0xc000, 0x2, 0x2100, 49152, 545)),
717                 "2001:db8:122:c000:2:2100:192.0.2.33".parse());
718
719         // colon after v4
720         let none: Option<Ipv4Addr> = "::127.0.0.1:".parse().ok();
721         assert_eq!(None, none);
722         // not enough groups
723         let none: Option<Ipv6Addr> = "1.2.3.4.5:127.0.0.1".parse().ok();
724         assert_eq!(None, none);
725         // too many groups
726         let none: Option<Ipv6Addr> = "1.2.3.4.5:6:7:127.0.0.1".parse().ok();
727         assert_eq!(None, none);
728     }
729
730     #[test]
731     fn test_from_str_socket_addr() {
732         assert_eq!(Ok(sa4(Ipv4Addr::new(77, 88, 21, 11), 80)),
733                    "77.88.21.11:80".parse());
734         assert_eq!(Ok(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80)),
735                    "77.88.21.11:80".parse());
736         assert_eq!(Ok(sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53)),
737                    "[2a02:6b8:0:1::1]:53".parse());
738         assert_eq!(Ok(SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1,
739                                                       0, 0, 0, 1), 53, 0, 0)),
740                    "[2a02:6b8:0:1::1]:53".parse());
741         assert_eq!(Ok(sa6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7F00, 1), 22)),
742                    "[::127.0.0.1]:22".parse());
743         assert_eq!(Ok(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0,
744                                                       0x7F00, 1), 22, 0, 0)),
745                    "[::127.0.0.1]:22".parse());
746
747         // without port
748         let none: Option<SocketAddr> = "127.0.0.1".parse().ok();
749         assert_eq!(None, none);
750         // without port
751         let none: Option<SocketAddr> = "127.0.0.1:".parse().ok();
752         assert_eq!(None, none);
753         // wrong brackets around v4
754         let none: Option<SocketAddr> = "[127.0.0.1]:22".parse().ok();
755         assert_eq!(None, none);
756         // port out of range
757         let none: Option<SocketAddr> = "127.0.0.1:123456".parse().ok();
758         assert_eq!(None, none);
759     }
760
761     #[test]
762     fn ipv6_addr_to_string() {
763         // ipv4-mapped address
764         let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280);
765         assert_eq!(a1.to_string(), "::ffff:192.0.2.128");
766
767         // ipv4-compatible address
768         let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x280);
769         assert_eq!(a1.to_string(), "::192.0.2.128");
770
771         // v6 address with no zero segments
772         assert_eq!(Ipv6Addr::new(8, 9, 10, 11, 12, 13, 14, 15).to_string(),
773                    "8:9:a:b:c:d:e:f");
774
775         // reduce a single run of zeros
776         assert_eq!("ae::ffff:102:304",
777                    Ipv6Addr::new(0xae, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304).to_string());
778
779         // don't reduce just a single zero segment
780         assert_eq!("1:2:3:4:5:6:0:8",
781                    Ipv6Addr::new(1, 2, 3, 4, 5, 6, 0, 8).to_string());
782
783         // 'any' address
784         assert_eq!("::", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).to_string());
785
786         // loopback address
787         assert_eq!("::1", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_string());
788
789         // ends in zeros
790         assert_eq!("1::", Ipv6Addr::new(1, 0, 0, 0, 0, 0, 0, 0).to_string());
791
792         // two runs of zeros, second one is longer
793         assert_eq!("1:0:0:4::8", Ipv6Addr::new(1, 0, 0, 4, 0, 0, 0, 8).to_string());
794
795         // two runs of zeros, equal length
796         assert_eq!("1::4:5:0:0:8", Ipv6Addr::new(1, 0, 0, 4, 5, 0, 0, 8).to_string());
797     }
798
799     #[test]
800     fn ipv4_to_ipv6() {
801         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678),
802                    Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_mapped());
803         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678),
804                    Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_compatible());
805     }
806
807     #[test]
808     fn ipv6_to_ipv4() {
809         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678).to_ipv4(),
810                    Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
811         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
812                    Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
813         assert_eq!(Ipv6Addr::new(0, 0, 1, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
814                    None);
815     }
816
817     #[test]
818     fn ip_properties() {
819         fn check4(octets: &[u8; 4], unspec: bool, loopback: bool,
820                   global: bool, multicast: bool, documentation: bool) {
821             let ip = IpAddr::V4(Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]));
822             assert_eq!(ip.is_unspecified(), unspec);
823             assert_eq!(ip.is_loopback(), loopback);
824             assert_eq!(ip.is_global(), global);
825             assert_eq!(ip.is_multicast(), multicast);
826             assert_eq!(ip.is_documentation(), documentation);
827         }
828
829         fn check6(str_addr: &str, unspec: bool, loopback: bool,
830                   global: bool, u_doc: bool, mcast: bool) {
831             let ip = IpAddr::V6(str_addr.parse().unwrap());
832             assert_eq!(ip.is_unspecified(), unspec);
833             assert_eq!(ip.is_loopback(), loopback);
834             assert_eq!(ip.is_global(), global);
835             assert_eq!(ip.is_documentation(), u_doc);
836             assert_eq!(ip.is_multicast(), mcast);
837         }
838
839         //     address                unspec loopbk global multicast doc
840         check4(&[0, 0, 0, 0],         true,  false, false,  false,   false);
841         check4(&[0, 0, 0, 1],         false, false, true,   false,   false);
842         check4(&[0, 1, 0, 0],         false, false, true,   false,   false);
843         check4(&[10, 9, 8, 7],        false, false, false,  false,   false);
844         check4(&[127, 1, 2, 3],       false, true,  false,  false,   false);
845         check4(&[172, 31, 254, 253],  false, false, false,  false,   false);
846         check4(&[169, 254, 253, 242], false, false, false,  false,   false);
847         check4(&[192, 0, 2, 183],     false, false, false,  false,   true);
848         check4(&[192, 1, 2, 183],     false, false, true,   false,   false);
849         check4(&[192, 168, 254, 253], false, false, false,  false,   false);
850         check4(&[198, 51, 100, 0],    false, false, false,  false,   true);
851         check4(&[203, 0, 113, 0],     false, false, false,  false,   true);
852         check4(&[203, 2, 113, 0],     false, false, true,   false,   false);
853         check4(&[224, 0, 0, 0],       false, false, true,   true,    false);
854         check4(&[239, 255, 255, 255], false, false, true,   true,    false);
855         check4(&[255, 255, 255, 255], false, false, false,  false,   false);
856
857         //     address                            unspec loopbk global doc    mcast
858         check6("::",                              true,  false, false, false, false);
859         check6("::1",                             false, true,  false, false, false);
860         check6("::0.0.0.2",                       false, false, true,  false, false);
861         check6("1::",                             false, false, true,  false, false);
862         check6("fc00::",                          false, false, false, false, false);
863         check6("fdff:ffff::",                     false, false, false, false, false);
864         check6("fe80:ffff::",                     false, false, false, false, false);
865         check6("febf:ffff::",                     false, false, false, false, false);
866         check6("fec0::",                          false, false, false, false, false);
867         check6("ff01::",                          false, false, false, false, true);
868         check6("ff02::",                          false, false, false, false, true);
869         check6("ff03::",                          false, false, false, false, true);
870         check6("ff04::",                          false, false, false, false, true);
871         check6("ff05::",                          false, false, false, false, true);
872         check6("ff08::",                          false, false, false, false, true);
873         check6("ff0e::",                          false, false, true,  false, true);
874         check6("2001:db8:85a3::8a2e:370:7334",    false, false, false, true,  false);
875         check6("102:304:506:708:90a:b0c:d0e:f10", false, false, true,  false, false);
876     }
877
878     #[test]
879     fn ipv4_properties() {
880         fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
881                  private: bool, link_local: bool, global: bool,
882                  multicast: bool, broadcast: bool, documentation: bool) {
883             let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
884             assert_eq!(octets, &ip.octets());
885
886             assert_eq!(ip.is_unspecified(), unspec);
887             assert_eq!(ip.is_loopback(), loopback);
888             assert_eq!(ip.is_private(), private);
889             assert_eq!(ip.is_link_local(), link_local);
890             assert_eq!(ip.is_global(), global);
891             assert_eq!(ip.is_multicast(), multicast);
892             assert_eq!(ip.is_broadcast(), broadcast);
893             assert_eq!(ip.is_documentation(), documentation);
894         }
895
896         //    address                unspec loopbk privt  linloc global multicast brdcast doc
897         check(&[0, 0, 0, 0],         true,  false, false, false, false,  false,    false,  false);
898         check(&[0, 0, 0, 1],         false, false, false, false, true,   false,    false,  false);
899         check(&[0, 1, 0, 0],         false, false, false, false, true,   false,    false,  false);
900         check(&[10, 9, 8, 7],        false, false, true,  false, false,  false,    false,  false);
901         check(&[127, 1, 2, 3],       false, true,  false, false, false,  false,    false,  false);
902         check(&[172, 31, 254, 253],  false, false, true,  false, false,  false,    false,  false);
903         check(&[169, 254, 253, 242], false, false, false, true,  false,  false,    false,  false);
904         check(&[192, 0, 2, 183],     false, false, false, false, false,  false,    false,  true);
905         check(&[192, 1, 2, 183],     false, false, false, false, true,   false,    false,  false);
906         check(&[192, 168, 254, 253], false, false, true,  false, false,  false,    false,  false);
907         check(&[198, 51, 100, 0],    false, false, false, false, false,  false,    false,  true);
908         check(&[203, 0, 113, 0],     false, false, false, false, false,  false,    false,  true);
909         check(&[203, 2, 113, 0],     false, false, false, false, true,   false,    false,  false);
910         check(&[224, 0, 0, 0],       false, false, false, false, true,   true,     false,  false);
911         check(&[239, 255, 255, 255], false, false, false, false, true,   true,     false,  false);
912         check(&[255, 255, 255, 255], false, false, false, false, false,  false,    true,   false);
913     }
914
915     #[test]
916     fn ipv6_properties() {
917         fn check(str_addr: &str, octets: &[u8; 16], unspec: bool, loopback: bool,
918                  unique_local: bool, global: bool,
919                  u_link_local: bool, u_site_local: bool, u_global: bool, u_doc: bool,
920                  m_scope: Option<Ipv6MulticastScope>) {
921             let ip: Ipv6Addr = str_addr.parse().unwrap();
922             assert_eq!(str_addr, ip.to_string());
923             assert_eq!(&ip.octets(), octets);
924             assert_eq!(Ipv6Addr::from(*octets), ip);
925
926             assert_eq!(ip.is_unspecified(), unspec);
927             assert_eq!(ip.is_loopback(), loopback);
928             assert_eq!(ip.is_unique_local(), unique_local);
929             assert_eq!(ip.is_global(), global);
930             assert_eq!(ip.is_unicast_link_local(), u_link_local);
931             assert_eq!(ip.is_unicast_site_local(), u_site_local);
932             assert_eq!(ip.is_unicast_global(), u_global);
933             assert_eq!(ip.is_documentation(), u_doc);
934             assert_eq!(ip.multicast_scope(), m_scope);
935             assert_eq!(ip.is_multicast(), m_scope.is_some());
936         }
937
938         //    unspec loopbk uniqlo global unill  unisl  uniglo doc    mscope
939         check("::", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
940               true,  false, false, false, false, false, false, false, None);
941         check("::1", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
942               false, true,  false, false, false, false, false, false, None);
943         check("::0.0.0.2", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2],
944               false, false, false, true,  false, false, true,  false, None);
945         check("1::", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
946               false, false, false, true,  false, false, true,  false, None);
947         check("fc00::", &[0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
948               false, false, true,  false, false, false, false, false, None);
949         check("fdff:ffff::", &[0xfd, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
950               false, false, true,  false, false, false, false, false, None);
951         check("fe80:ffff::", &[0xfe, 0x80, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
952               false, false, false, false, true,  false, false, false, None);
953         check("febf:ffff::", &[0xfe, 0xbf, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
954               false, false, false, false, true,  false, false, false, None);
955         check("fec0::", &[0xfe, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
956               false, false, false, false, false, true,  false, false, None);
957         check("ff01::", &[0xff, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
958               false, false, false, false, false, false, false, false, Some(InterfaceLocal));
959         check("ff02::", &[0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
960               false, false, false, false, false, false, false, false, Some(LinkLocal));
961         check("ff03::", &[0xff, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
962               false, false, false, false, false, false, false, false, Some(RealmLocal));
963         check("ff04::", &[0xff, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
964               false, false, false, false, false, false, false, false, Some(AdminLocal));
965         check("ff05::", &[0xff, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
966               false, false, false, false, false, false, false, false, Some(SiteLocal));
967         check("ff08::", &[0xff, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
968               false, false, false, false, false, false, false, false, Some(OrganizationLocal));
969         check("ff0e::", &[0xff, 0xe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
970               false, false, false, true,  false, false, false, false, Some(Global));
971         check("2001:db8:85a3::8a2e:370:7334",
972               &[0x20, 1, 0xd, 0xb8, 0x85, 0xa3, 0, 0, 0, 0, 0x8a, 0x2e, 3, 0x70, 0x73, 0x34],
973               false, false, false, false, false, false, false, true, None);
974         check("102:304:506:708:90a:b0c:d0e:f10",
975               &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
976               false, false, false, true,  false, false, true,  false, None);
977     }
978
979     #[test]
980     fn to_socket_addr_socketaddr() {
981         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 12345);
982         assert_eq!(Ok(vec![a]), tsa(a));
983     }
984
985     #[test]
986     fn test_ipv4_to_int() {
987         let a = Ipv4Addr::new(127, 0, 0, 1);
988         assert_eq!(u32::from(a), 2130706433);
989     }
990
991     #[test]
992     fn test_int_to_ipv4() {
993         let a = Ipv4Addr::new(127, 0, 0, 1);
994         assert_eq!(Ipv4Addr::from(2130706433), a);
995     }
996
997     #[test]
998     fn ipv4_from_u32_slice() {
999         assert_eq!(Ipv4Addr::from([127, 0, 0, 1]), Ipv4Addr::new(127, 0, 0, 1))
1000     }
1001
1002     #[test]
1003     fn ord() {
1004         assert!(Ipv4Addr::new(100, 64, 3, 3) < Ipv4Addr::new(192, 0, 2, 2));
1005         assert!("2001:db8:f00::1002".parse::<Ipv6Addr>().unwrap() <
1006                 "2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap());
1007     }
1008 }