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