|
8 | 8 | // option. This file may not be copied, modified, or distributed
|
9 | 9 | // except according to those terms.
|
10 | 10 |
|
| 11 | +use num::FromStrRadix; |
| 12 | +use to_str::ToStr; |
| 13 | + |
11 | 14 | type Port = u16;
|
12 | 15 |
|
13 | 16 | #[deriving(Eq, TotalEq)]
|
14 | 17 | pub enum IpAddr {
|
15 | 18 | Ipv4(u8, u8, u8, u8, Port),
|
16 | 19 | Ipv6(u16, u16, u16, u16, u16, u16, u16, u16, Port)
|
17 | 20 | }
|
| 21 | + |
| 22 | +impl ToStr for IpAddr { |
| 23 | + fn to_str(&self) -> ~str { |
| 24 | + match *self { |
| 25 | + Ipv4(a, b, c, d, p) => |
| 26 | + fmt!("%u.%u.%u.%u:%u", |
| 27 | + a as uint, b as uint, c as uint, d as uint, p as uint), |
| 28 | + |
| 29 | + // Ipv4 Compatible address |
| 30 | + Ipv6(0, 0, 0, 0, 0, 0, g, h, p) => { |
| 31 | + let a = fmt!("%04x", g as uint); |
| 32 | + let b = FromStrRadix::from_str_radix(a.slice(2, 4), 16).unwrap(); |
| 33 | + let a = FromStrRadix::from_str_radix(a.slice(0, 2), 16).unwrap(); |
| 34 | + let c = fmt!("%04x", h as uint); |
| 35 | + let d = FromStrRadix::from_str_radix(c.slice(2, 4), 16).unwrap(); |
| 36 | + let c = FromStrRadix::from_str_radix(c.slice(0, 2), 16).unwrap(); |
| 37 | + |
| 38 | + fmt!("[::%u.%u.%u.%u]:%u", a, b, c, d, p as uint) |
| 39 | + } |
| 40 | + |
| 41 | + // Ipv4-Mapped address |
| 42 | + Ipv6(0, 0, 0, 0, 0, 1, g, h, p) => { |
| 43 | + let a = fmt!("%04x", g as uint); |
| 44 | + let b = FromStrRadix::from_str_radix(a.slice(2, 4), 16).unwrap(); |
| 45 | + let a = FromStrRadix::from_str_radix(a.slice(0, 2), 16).unwrap(); |
| 46 | + let c = fmt!("%04x", h as uint); |
| 47 | + let d = FromStrRadix::from_str_radix(c.slice(2, 4), 16).unwrap(); |
| 48 | + let c = FromStrRadix::from_str_radix(c.slice(0, 2), 16).unwrap(); |
| 49 | + |
| 50 | + fmt!("[::FFFF:%u.%u.%u.%u]:%u", a, b, c, d, p as uint) |
| 51 | + } |
| 52 | + |
| 53 | + Ipv6(a, b, c, d, e, f, g, h, p) => |
| 54 | + fmt!("[%x:%x:%x:%x:%x:%x:%x:%x]:%u", |
| 55 | + a as uint, b as uint, c as uint, d as uint, |
| 56 | + e as uint, f as uint, g as uint, h as uint, p as uint) |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments