]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/ip.rs
Auto merge of #32073 - jseyfried:fix_another_trait_privacy_error, r=nikomatsakis
[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 Ipv4Addr {
63     /// Creates a new IPv4 address from four eight-bit octets.
64     ///
65     /// The result will represent the IP address `a`.`b`.`c`.`d`.
66     #[stable(feature = "rust1", since = "1.0.0")]
67     pub fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
68         Ipv4Addr {
69             inner: c::in_addr {
70                 s_addr: hton(((a as u32) << 24) |
71                              ((b as u32) << 16) |
72                              ((c as u32) <<  8) |
73                               (d as u32)),
74             }
75         }
76     }
77
78     /// Returns the four eight-bit integers that make up this address.
79     #[stable(feature = "rust1", since = "1.0.0")]
80     pub fn octets(&self) -> [u8; 4] {
81         let bits = ntoh(self.inner.s_addr);
82         [(bits >> 24) as u8, (bits >> 16) as u8, (bits >> 8) as u8, bits as u8]
83     }
84
85     /// Returns true for the special 'unspecified' address 0.0.0.0.
86     pub fn is_unspecified(&self) -> bool {
87         self.inner.s_addr == 0
88     }
89
90     /// Returns true if this is a loopback address (127.0.0.0/8).
91     ///
92     /// This property is defined by RFC 6890
93     #[stable(since = "1.7.0", feature = "ip_17")]
94     pub fn is_loopback(&self) -> bool {
95         self.octets()[0] == 127
96     }
97
98     /// Returns true if this is a private address.
99     ///
100     /// The private address ranges are defined in RFC1918 and include:
101     ///
102     ///  - 10.0.0.0/8
103     ///  - 172.16.0.0/12
104     ///  - 192.168.0.0/16
105     #[stable(since = "1.7.0", feature = "ip_17")]
106     pub fn is_private(&self) -> bool {
107         match (self.octets()[0], self.octets()[1]) {
108             (10, _) => true,
109             (172, b) if b >= 16 && b <= 31 => true,
110             (192, 168) => true,
111             _ => false
112         }
113     }
114
115     /// Returns true if the address is link-local (169.254.0.0/16).
116     ///
117     /// This property is defined by RFC 6890
118     #[stable(since = "1.7.0", feature = "ip_17")]
119     pub fn is_link_local(&self) -> bool {
120         self.octets()[0] == 169 && self.octets()[1] == 254
121     }
122
123     /// Returns true if the address appears to be globally routable.
124     /// See [iana-ipv4-special-registry][ipv4-sr].
125     /// [ipv4-sr]: http://goo.gl/RaZ7lg
126     ///
127     /// The following return false:
128     ///
129     /// - private address (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16)
130     /// - the loopback address (127.0.0.0/8)
131     /// - the link-local address (169.254.0.0/16)
132     /// - the broadcast address (255.255.255.255/32)
133     /// - test addresses used for documentation (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24)
134     /// - the unspecified address (0.0.0.0)
135     pub fn is_global(&self) -> bool {
136         !self.is_private() && !self.is_loopback() && !self.is_link_local() &&
137         !self.is_broadcast() && !self.is_documentation() && !self.is_unspecified()
138     }
139
140     /// Returns true if this is a multicast address.
141     ///
142     /// Multicast addresses have a most significant octet between 224 and 239,
143     /// and is defined by RFC 5771
144     #[stable(since = "1.7.0", feature = "ip_17")]
145     pub fn is_multicast(&self) -> bool {
146         self.octets()[0] >= 224 && self.octets()[0] <= 239
147     }
148
149     /// Returns true if this is a broadcast address.
150     ///
151     /// A broadcast address has all octets set to 255 as defined in RFC 919.
152     #[stable(since = "1.7.0", feature = "ip_17")]
153     pub fn is_broadcast(&self) -> bool {
154         self.octets()[0] == 255 && self.octets()[1] == 255 &&
155         self.octets()[2] == 255 && self.octets()[3] == 255
156     }
157
158     /// Returns true if this address is in a range designated for documentation.
159     ///
160     /// This is defined in RFC 5737:
161     ///
162     /// - 192.0.2.0/24 (TEST-NET-1)
163     /// - 198.51.100.0/24 (TEST-NET-2)
164     /// - 203.0.113.0/24 (TEST-NET-3)
165     #[stable(since = "1.7.0", feature = "ip_17")]
166     pub fn is_documentation(&self) -> bool {
167         match(self.octets()[0], self.octets()[1], self.octets()[2], self.octets()[3]) {
168             (192, 0, 2, _) => true,
169             (198, 51, 100, _) => true,
170             (203, 0, 113, _) => true,
171             _ => false
172         }
173     }
174
175     /// Converts this address to an IPv4-compatible IPv6 address.
176     ///
177     /// a.b.c.d becomes ::a.b.c.d
178     #[stable(feature = "rust1", since = "1.0.0")]
179     pub fn to_ipv6_compatible(&self) -> Ipv6Addr {
180         Ipv6Addr::new(0, 0, 0, 0, 0, 0,
181                       ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
182                       ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
183     }
184
185     /// Converts this address to an IPv4-mapped IPv6 address.
186     ///
187     /// a.b.c.d becomes ::ffff:a.b.c.d
188     #[stable(feature = "rust1", since = "1.0.0")]
189     pub fn to_ipv6_mapped(&self) -> Ipv6Addr {
190         Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff,
191                       ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
192                       ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
193     }
194 }
195
196 #[stable(feature = "rust1", since = "1.0.0")]
197 #[allow(deprecated)]
198 impl fmt::Display for IpAddr {
199     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
200         match *self {
201             IpAddr::V4(ref a) => a.fmt(fmt),
202             IpAddr::V6(ref a) => a.fmt(fmt),
203         }
204     }
205 }
206
207 #[stable(feature = "rust1", since = "1.0.0")]
208 impl fmt::Display for Ipv4Addr {
209     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
210         let octets = self.octets();
211         write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
212     }
213 }
214
215 #[stable(feature = "rust1", since = "1.0.0")]
216 impl fmt::Debug for Ipv4Addr {
217     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
218         fmt::Display::fmt(self, fmt)
219     }
220 }
221
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl Clone for Ipv4Addr {
224     fn clone(&self) -> Ipv4Addr { *self }
225 }
226
227 #[stable(feature = "rust1", since = "1.0.0")]
228 impl PartialEq for Ipv4Addr {
229     fn eq(&self, other: &Ipv4Addr) -> bool {
230         self.inner.s_addr == other.inner.s_addr
231     }
232 }
233
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl Eq for Ipv4Addr {}
236
237 #[stable(feature = "rust1", since = "1.0.0")]
238 impl hash::Hash for Ipv4Addr {
239     fn hash<H: hash::Hasher>(&self, s: &mut H) {
240         self.inner.s_addr.hash(s)
241     }
242 }
243
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl PartialOrd for Ipv4Addr {
246     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
247         Some(self.cmp(other))
248     }
249 }
250
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl Ord for Ipv4Addr {
253     fn cmp(&self, other: &Ipv4Addr) -> Ordering {
254         self.octets().cmp(&other.octets())
255     }
256 }
257
258 impl AsInner<c::in_addr> for Ipv4Addr {
259     fn as_inner(&self) -> &c::in_addr { &self.inner }
260 }
261 impl FromInner<c::in_addr> for Ipv4Addr {
262     fn from_inner(addr: c::in_addr) -> Ipv4Addr {
263         Ipv4Addr { inner: addr }
264     }
265 }
266
267 #[stable(feature = "ip_u32", since = "1.1.0")]
268 impl From<Ipv4Addr> for u32 {
269     fn from(ip: Ipv4Addr) -> u32 {
270         let ip = ip.octets();
271         ((ip[0] as u32) << 24) + ((ip[1] as u32) << 16) + ((ip[2] as u32) << 8) + (ip[3] as u32)
272     }
273 }
274
275 #[stable(feature = "ip_u32", since = "1.1.0")]
276 impl From<u32> for Ipv4Addr {
277     fn from(ip: u32) -> Ipv4Addr {
278         Ipv4Addr::new((ip >> 24) as u8, (ip >> 16) as u8, (ip >> 8) as u8, ip as u8)
279     }
280 }
281
282 impl Ipv6Addr {
283     /// Creates a new IPv6 address from eight 16-bit segments.
284     ///
285     /// The result will represent the IP address a:b:c:d:e:f:g:h.
286     #[stable(feature = "rust1", since = "1.0.0")]
287     pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16,
288                h: u16) -> Ipv6Addr {
289         let mut addr: c::in6_addr = unsafe { mem::zeroed() };
290         addr.s6_addr = [(a >> 8) as u8, a as u8,
291                         (b >> 8) as u8, b as u8,
292                         (c >> 8) as u8, c as u8,
293                         (d >> 8) as u8, d as u8,
294                         (e >> 8) as u8, e as u8,
295                         (f >> 8) as u8, f as u8,
296                         (g >> 8) as u8, g as u8,
297                         (h >> 8) as u8, h as u8];
298         Ipv6Addr { inner: addr }
299     }
300
301     /// Returns the eight 16-bit segments that make up this address.
302     #[stable(feature = "rust1", since = "1.0.0")]
303     pub fn segments(&self) -> [u16; 8] {
304         let arr = &self.inner.s6_addr;
305         [
306             (arr[0] as u16) << 8 | (arr[1] as u16),
307             (arr[2] as u16) << 8 | (arr[3] as u16),
308             (arr[4] as u16) << 8 | (arr[5] as u16),
309             (arr[6] as u16) << 8 | (arr[7] as u16),
310             (arr[8] as u16) << 8 | (arr[9] as u16),
311             (arr[10] as u16) << 8 | (arr[11] as u16),
312             (arr[12] as u16) << 8 | (arr[13] as u16),
313             (arr[14] as u16) << 8 | (arr[15] as u16),
314         ]
315     }
316
317     /// Returns true for the special 'unspecified' address ::.
318     ///
319     /// This property is defined in RFC 6890.
320     #[stable(since = "1.7.0", feature = "ip_17")]
321     pub fn is_unspecified(&self) -> bool {
322         self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
323     }
324
325     /// Returns true if this is a loopback address (::1).
326     ///
327     /// This property is defined in RFC 6890.
328     #[stable(since = "1.7.0", feature = "ip_17")]
329     pub fn is_loopback(&self) -> bool {
330         self.segments() == [0, 0, 0, 0, 0, 0, 0, 1]
331     }
332
333     /// Returns true if the address appears to be globally routable.
334     ///
335     /// The following return false:
336     ///
337     /// - the loopback address
338     /// - link-local, site-local, and unique local unicast addresses
339     /// - interface-, link-, realm-, admin- and site-local multicast addresses
340     pub fn is_global(&self) -> bool {
341         match self.multicast_scope() {
342             Some(Ipv6MulticastScope::Global) => true,
343             None => self.is_unicast_global(),
344             _ => false
345         }
346     }
347
348     /// Returns true if this is a unique local address (IPv6).
349     ///
350     /// Unique local addresses are defined in RFC4193 and have the form fc00::/7.
351     pub fn is_unique_local(&self) -> bool {
352         (self.segments()[0] & 0xfe00) == 0xfc00
353     }
354
355     /// Returns true if the address is unicast and link-local (fe80::/10).
356     pub fn is_unicast_link_local(&self) -> bool {
357         (self.segments()[0] & 0xffc0) == 0xfe80
358     }
359
360     /// Returns true if this is a deprecated unicast site-local address (IPv6
361     /// fec0::/10).
362     pub fn is_unicast_site_local(&self) -> bool {
363         (self.segments()[0] & 0xffc0) == 0xfec0
364     }
365
366     /// Returns true if the address is a globally routable unicast address.
367     ///
368     /// The following return false:
369     ///
370     /// - the loopback address
371     /// - the link-local addresses
372     /// - the (deprecated) site-local addresses
373     /// - unique local addresses
374     pub fn is_unicast_global(&self) -> bool {
375         !self.is_multicast()
376             && !self.is_loopback() && !self.is_unicast_link_local()
377             && !self.is_unicast_site_local() && !self.is_unique_local()
378     }
379
380     /// Returns the address's multicast scope if the address is multicast.
381     pub fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
382         if self.is_multicast() {
383             match self.segments()[0] & 0x000f {
384                 1 => Some(Ipv6MulticastScope::InterfaceLocal),
385                 2 => Some(Ipv6MulticastScope::LinkLocal),
386                 3 => Some(Ipv6MulticastScope::RealmLocal),
387                 4 => Some(Ipv6MulticastScope::AdminLocal),
388                 5 => Some(Ipv6MulticastScope::SiteLocal),
389                 8 => Some(Ipv6MulticastScope::OrganizationLocal),
390                 14 => Some(Ipv6MulticastScope::Global),
391                 _ => None
392             }
393         } else {
394             None
395         }
396     }
397
398     /// Returns true if this is a multicast address.
399     ///
400     /// Multicast addresses have the form ff00::/8, and this property is defined
401     /// by RFC 3956.
402     #[stable(since = "1.7.0", feature = "ip_17")]
403     pub fn is_multicast(&self) -> bool {
404         (self.segments()[0] & 0xff00) == 0xff00
405     }
406
407     /// Converts this address to an IPv4 address. Returns None if this address is
408     /// neither IPv4-compatible or IPv4-mapped.
409     ///
410     /// ::a.b.c.d and ::ffff:a.b.c.d become a.b.c.d
411     #[stable(feature = "rust1", since = "1.0.0")]
412     pub fn to_ipv4(&self) -> Option<Ipv4Addr> {
413         match self.segments() {
414             [0, 0, 0, 0, 0, f, g, h] if f == 0 || f == 0xffff => {
415                 Some(Ipv4Addr::new((g >> 8) as u8, g as u8,
416                                    (h >> 8) as u8, h as u8))
417             },
418             _ => None
419         }
420     }
421 }
422
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl fmt::Display for Ipv6Addr {
425     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
426         match self.segments() {
427             // We need special cases for :: and ::1, otherwise they're formatted
428             // as ::0.0.0.[01]
429             [0, 0, 0, 0, 0, 0, 0, 0] => write!(fmt, "::"),
430             [0, 0, 0, 0, 0, 0, 0, 1] => write!(fmt, "::1"),
431             // Ipv4 Compatible address
432             [0, 0, 0, 0, 0, 0, g, h] => {
433                 write!(fmt, "::{}.{}.{}.{}", (g >> 8) as u8, g as u8,
434                        (h >> 8) as u8, h as u8)
435             }
436             // Ipv4-Mapped address
437             [0, 0, 0, 0, 0, 0xffff, g, h] => {
438                 write!(fmt, "::ffff:{}.{}.{}.{}", (g >> 8) as u8, g as u8,
439                        (h >> 8) as u8, h as u8)
440             },
441             _ => {
442                 fn find_zero_slice(segments: &[u16; 8]) -> (usize, usize) {
443                     let mut longest_span_len = 0;
444                     let mut longest_span_at = 0;
445                     let mut cur_span_len = 0;
446                     let mut cur_span_at = 0;
447
448                     for i in 0..8 {
449                         if segments[i] == 0 {
450                             if cur_span_len == 0 {
451                                 cur_span_at = i;
452                             }
453
454                             cur_span_len += 1;
455
456                             if cur_span_len > longest_span_len {
457                                 longest_span_len = cur_span_len;
458                                 longest_span_at = cur_span_at;
459                             }
460                         } else {
461                             cur_span_len = 0;
462                             cur_span_at = 0;
463                         }
464                     }
465
466                     (longest_span_at, longest_span_len)
467                 }
468
469                 let (zeros_at, zeros_len) = find_zero_slice(&self.segments());
470
471                 if zeros_len > 1 {
472                     fn fmt_subslice(segments: &[u16], fmt: &mut fmt::Formatter) -> fmt::Result {
473                         if !segments.is_empty() {
474                             try!(write!(fmt, "{:x}", segments[0]));
475                             for &seg in &segments[1..] {
476                                 try!(write!(fmt, ":{:x}", seg));
477                             }
478                         }
479                         Ok(())
480                     }
481
482                     try!(fmt_subslice(&self.segments()[..zeros_at], fmt));
483                     try!(fmt.write_str("::"));
484                     fmt_subslice(&self.segments()[zeros_at + zeros_len..], fmt)
485                 } else {
486                     let &[a, b, c, d, e, f, g, h] = &self.segments();
487                     write!(fmt, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
488                            a, b, c, d, e, f, g, h)
489                 }
490             }
491         }
492     }
493 }
494
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl fmt::Debug for Ipv6Addr {
497     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
498         fmt::Display::fmt(self, fmt)
499     }
500 }
501
502 #[stable(feature = "rust1", since = "1.0.0")]
503 impl Clone for Ipv6Addr {
504     fn clone(&self) -> Ipv6Addr { *self }
505 }
506
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl PartialEq for Ipv6Addr {
509     fn eq(&self, other: &Ipv6Addr) -> bool {
510         self.inner.s6_addr == other.inner.s6_addr
511     }
512 }
513
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl Eq for Ipv6Addr {}
516
517 #[stable(feature = "rust1", since = "1.0.0")]
518 impl hash::Hash for Ipv6Addr {
519     fn hash<H: hash::Hasher>(&self, s: &mut H) {
520         self.inner.s6_addr.hash(s)
521     }
522 }
523
524 #[stable(feature = "rust1", since = "1.0.0")]
525 impl PartialOrd for Ipv6Addr {
526     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
527         Some(self.cmp(other))
528     }
529 }
530
531 #[stable(feature = "rust1", since = "1.0.0")]
532 impl Ord for Ipv6Addr {
533     fn cmp(&self, other: &Ipv6Addr) -> Ordering {
534         self.segments().cmp(&other.segments())
535     }
536 }
537
538 impl AsInner<c::in6_addr> for Ipv6Addr {
539     fn as_inner(&self) -> &c::in6_addr { &self.inner }
540 }
541 impl FromInner<c::in6_addr> for Ipv6Addr {
542     fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
543         Ipv6Addr { inner: addr }
544     }
545 }
546
547 // Tests for this module
548 #[cfg(test)]
549 mod tests {
550     use prelude::v1::*;
551     use net::*;
552     use net::Ipv6MulticastScope::*;
553     use net::test::{tsa, sa6, sa4};
554
555     #[test]
556     fn test_from_str_ipv4() {
557         assert_eq!(Ok(Ipv4Addr::new(127, 0, 0, 1)), "127.0.0.1".parse());
558         assert_eq!(Ok(Ipv4Addr::new(255, 255, 255, 255)), "255.255.255.255".parse());
559         assert_eq!(Ok(Ipv4Addr::new(0, 0, 0, 0)), "0.0.0.0".parse());
560
561         // out of range
562         let none: Option<Ipv4Addr> = "256.0.0.1".parse().ok();
563         assert_eq!(None, none);
564         // too short
565         let none: Option<Ipv4Addr> = "255.0.0".parse().ok();
566         assert_eq!(None, none);
567         // too long
568         let none: Option<Ipv4Addr> = "255.0.0.1.2".parse().ok();
569         assert_eq!(None, none);
570         // no number between dots
571         let none: Option<Ipv4Addr> = "255.0..1".parse().ok();
572         assert_eq!(None, none);
573     }
574
575     #[test]
576     fn test_from_str_ipv6() {
577         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "0:0:0:0:0:0:0:0".parse());
578         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "0:0:0:0:0:0:0:1".parse());
579
580         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "::1".parse());
581         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "::".parse());
582
583         assert_eq!(Ok(Ipv6Addr::new(0x2a02, 0x6b8, 0, 0, 0, 0, 0x11, 0x11)),
584                 "2a02:6b8::11:11".parse());
585
586         // too long group
587         let none: Option<Ipv6Addr> = "::00000".parse().ok();
588         assert_eq!(None, none);
589         // too short
590         let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7".parse().ok();
591         assert_eq!(None, none);
592         // too long
593         let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7:8:9".parse().ok();
594         assert_eq!(None, none);
595         // triple colon
596         let none: Option<Ipv6Addr> = "1:2:::6:7:8".parse().ok();
597         assert_eq!(None, none);
598         // two double colons
599         let none: Option<Ipv6Addr> = "1:2::6::8".parse().ok();
600         assert_eq!(None, none);
601     }
602
603     #[test]
604     fn test_from_str_ipv4_in_ipv6() {
605         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 545)),
606                 "::192.0.2.33".parse());
607         assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0xFFFF, 49152, 545)),
608                 "::FFFF:192.0.2.33".parse());
609         assert_eq!(Ok(Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 49152, 545)),
610                 "64:ff9b::192.0.2.33".parse());
611         assert_eq!(Ok(Ipv6Addr::new(0x2001, 0xdb8, 0x122, 0xc000, 0x2, 0x2100, 49152, 545)),
612                 "2001:db8:122:c000:2:2100:192.0.2.33".parse());
613
614         // colon after v4
615         let none: Option<Ipv4Addr> = "::127.0.0.1:".parse().ok();
616         assert_eq!(None, none);
617         // not enough groups
618         let none: Option<Ipv6Addr> = "1.2.3.4.5:127.0.0.1".parse().ok();
619         assert_eq!(None, none);
620         // too many groups
621         let none: Option<Ipv6Addr> = "1.2.3.4.5:6:7:127.0.0.1".parse().ok();
622         assert_eq!(None, none);
623     }
624
625     #[test]
626     fn test_from_str_socket_addr() {
627         assert_eq!(Ok(sa4(Ipv4Addr::new(77, 88, 21, 11), 80)),
628                    "77.88.21.11:80".parse());
629         assert_eq!(Ok(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80)),
630                    "77.88.21.11:80".parse());
631         assert_eq!(Ok(sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53)),
632                    "[2a02:6b8:0:1::1]:53".parse());
633         assert_eq!(Ok(SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1,
634                                                       0, 0, 0, 1), 53, 0, 0)),
635                    "[2a02:6b8:0:1::1]:53".parse());
636         assert_eq!(Ok(sa6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7F00, 1), 22)),
637                    "[::127.0.0.1]:22".parse());
638         assert_eq!(Ok(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0,
639                                                       0x7F00, 1), 22, 0, 0)),
640                    "[::127.0.0.1]:22".parse());
641
642         // without port
643         let none: Option<SocketAddr> = "127.0.0.1".parse().ok();
644         assert_eq!(None, none);
645         // without port
646         let none: Option<SocketAddr> = "127.0.0.1:".parse().ok();
647         assert_eq!(None, none);
648         // wrong brackets around v4
649         let none: Option<SocketAddr> = "[127.0.0.1]:22".parse().ok();
650         assert_eq!(None, none);
651         // port out of range
652         let none: Option<SocketAddr> = "127.0.0.1:123456".parse().ok();
653         assert_eq!(None, none);
654     }
655
656     #[test]
657     fn ipv6_addr_to_string() {
658         // ipv4-mapped address
659         let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280);
660         assert_eq!(a1.to_string(), "::ffff:192.0.2.128");
661
662         // ipv4-compatible address
663         let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x280);
664         assert_eq!(a1.to_string(), "::192.0.2.128");
665
666         // v6 address with no zero segments
667         assert_eq!(Ipv6Addr::new(8, 9, 10, 11, 12, 13, 14, 15).to_string(),
668                    "8:9:a:b:c:d:e:f");
669
670         // reduce a single run of zeros
671         assert_eq!("ae::ffff:102:304",
672                    Ipv6Addr::new(0xae, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304).to_string());
673
674         // don't reduce just a single zero segment
675         assert_eq!("1:2:3:4:5:6:0:8",
676                    Ipv6Addr::new(1, 2, 3, 4, 5, 6, 0, 8).to_string());
677
678         // 'any' address
679         assert_eq!("::", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).to_string());
680
681         // loopback address
682         assert_eq!("::1", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_string());
683
684         // ends in zeros
685         assert_eq!("1::", Ipv6Addr::new(1, 0, 0, 0, 0, 0, 0, 0).to_string());
686
687         // two runs of zeros, second one is longer
688         assert_eq!("1:0:0:4::8", Ipv6Addr::new(1, 0, 0, 4, 0, 0, 0, 8).to_string());
689
690         // two runs of zeros, equal length
691         assert_eq!("1::4:5:0:0:8", Ipv6Addr::new(1, 0, 0, 4, 5, 0, 0, 8).to_string());
692     }
693
694     #[test]
695     fn ipv4_to_ipv6() {
696         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678),
697                    Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_mapped());
698         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678),
699                    Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_compatible());
700     }
701
702     #[test]
703     fn ipv6_to_ipv4() {
704         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678).to_ipv4(),
705                    Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
706         assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
707                    Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
708         assert_eq!(Ipv6Addr::new(0, 0, 1, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
709                    None);
710     }
711
712     #[test]
713     fn ipv4_properties() {
714         fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
715                  private: bool, link_local: bool, global: bool,
716                  multicast: bool, broadcast: bool, documentation: bool) {
717             let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
718             assert_eq!(octets, &ip.octets());
719
720             assert_eq!(ip.is_unspecified(), unspec);
721             assert_eq!(ip.is_loopback(), loopback);
722             assert_eq!(ip.is_private(), private);
723             assert_eq!(ip.is_link_local(), link_local);
724             assert_eq!(ip.is_global(), global);
725             assert_eq!(ip.is_multicast(), multicast);
726             assert_eq!(ip.is_broadcast(), broadcast);
727             assert_eq!(ip.is_documentation(), documentation);
728         }
729
730         //    address                unspec loopbk privt  linloc global multicast brdcast doc
731         check(&[0, 0, 0, 0],         true,  false, false, false, false,  false,    false,  false);
732         check(&[0, 0, 0, 1],         false, false, false, false, true,   false,    false,  false);
733         check(&[1, 0, 0, 0],         false, false, false, false, true,   false,    false,  false);
734         check(&[10, 9, 8, 7],        false, false, true,  false, false,  false,    false,  false);
735         check(&[127, 1, 2, 3],       false, true,  false, false, false,  false,    false,  false);
736         check(&[172, 31, 254, 253],  false, false, true,  false, false,  false,    false,  false);
737         check(&[169, 254, 253, 242], false, false, false, true,  false,  false,    false,  false);
738         check(&[192, 0, 2, 183],     false, false, false, false, false,  false,    false,  true);
739         check(&[192, 1, 2, 183],     false, false, false, false, true,   false,    false,  false);
740         check(&[192, 168, 254, 253], false, false, true,  false, false,  false,    false,  false);
741         check(&[198, 51, 100, 0],    false, false, false, false, false,  false,    false,  true);
742         check(&[203, 0, 113, 0],     false, false, false, false, false,  false,    false,  true);
743         check(&[203, 2, 113, 0],     false, false, false, false, true,   false,    false,  false);
744         check(&[224, 0, 0, 0],       false, false, false, false, true,   true,     false,  false);
745         check(&[239, 255, 255, 255], false, false, false, false, true,   true,     false,  false);
746         check(&[255, 255, 255, 255], false, false, false, false, false,  false,    true,   false);
747     }
748
749     #[test]
750     fn ipv6_properties() {
751         fn check(str_addr: &str, unspec: bool, loopback: bool,
752                  unique_local: bool, global: bool,
753                  u_link_local: bool, u_site_local: bool, u_global: bool,
754                  m_scope: Option<Ipv6MulticastScope>) {
755             let ip: Ipv6Addr = str_addr.parse().unwrap();
756             assert_eq!(str_addr, ip.to_string());
757
758             assert_eq!(ip.is_unspecified(), unspec);
759             assert_eq!(ip.is_loopback(), loopback);
760             assert_eq!(ip.is_unique_local(), unique_local);
761             assert_eq!(ip.is_global(), global);
762             assert_eq!(ip.is_unicast_link_local(), u_link_local);
763             assert_eq!(ip.is_unicast_site_local(), u_site_local);
764             assert_eq!(ip.is_unicast_global(), u_global);
765             assert_eq!(ip.multicast_scope(), m_scope);
766             assert_eq!(ip.is_multicast(), m_scope.is_some());
767         }
768
769         //    unspec loopbk uniqlo global unill  unisl  uniglo mscope
770         check("::",
771               true,  false, false, true,  false, false, true,  None);
772         check("::1",
773               false, true,  false, false, false, false, false, None);
774         check("::0.0.0.2",
775               false, false, false, true,  false, false, true,  None);
776         check("1::",
777               false, false, false, true,  false, false, true,  None);
778         check("fc00::",
779               false, false, true,  false, false, false, false, None);
780         check("fdff:ffff::",
781               false, false, true,  false, false, false, false, None);
782         check("fe80:ffff::",
783               false, false, false, false, true,  false, false, None);
784         check("febf:ffff::",
785               false, false, false, false, true,  false, false, None);
786         check("fec0::",
787               false, false, false, false, false, true,  false, None);
788         check("ff01::",
789               false, false, false, false, false, false, false, Some(InterfaceLocal));
790         check("ff02::",
791               false, false, false, false, false, false, false, Some(LinkLocal));
792         check("ff03::",
793               false, false, false, false, false, false, false, Some(RealmLocal));
794         check("ff04::",
795               false, false, false, false, false, false, false, Some(AdminLocal));
796         check("ff05::",
797               false, false, false, false, false, false, false, Some(SiteLocal));
798         check("ff08::",
799               false, false, false, false, false, false, false, Some(OrganizationLocal));
800         check("ff0e::",
801               false, false, false, true,  false, false, false, Some(Global));
802     }
803
804     #[test]
805     fn to_socket_addr_socketaddr() {
806         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 12345);
807         assert_eq!(Ok(vec![a]), tsa(a));
808     }
809
810     #[test]
811     fn test_ipv4_to_int() {
812         let a = Ipv4Addr::new(127, 0, 0, 1);
813         assert_eq!(u32::from(a), 2130706433);
814     }
815
816     #[test]
817     fn test_int_to_ipv4() {
818         let a = Ipv4Addr::new(127, 0, 0, 1);
819         assert_eq!(Ipv4Addr::from(2130706433), a);
820     }
821
822     #[test]
823     fn ord() {
824         assert!(Ipv4Addr::new(100, 64, 3, 3) < Ipv4Addr::new(192, 0, 2, 2));
825         assert!("2001:db8:f00::1002".parse::<Ipv6Addr>().unwrap() <
826                 "2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap());
827     }
828 }