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