rust/src/lib/net.rs

23 lines
626 B
Rust
Raw Normal View History

2011-08-15 18:38:23 -05:00
import vec;
import uint;
tag ip_addr { ipv4(u8, u8, u8, u8); }
2011-08-28 01:35:16 -05:00
fn format_addr(ip: ip_addr) -> istr {
alt ip {
ipv4(a, b, c, d) {
#ifmt["%u.%u.%u.%u", a as uint, b as uint, c as uint, d as uint]
}
_ { fail "Unsupported address type"; }
}
}
2011-08-28 01:35:16 -05:00
fn parse_addr(ip: &istr) -> ip_addr {
2011-08-23 22:25:23 -05:00
let parts = vec::map(
2011-08-28 01:35:16 -05:00
{ |&s| uint::from_str(s) },
str::split(ip, ~"."[0]));
2011-08-15 18:38:23 -05:00
if vec::len(parts) != 4u { fail "Too many dots in IP address"; }
for i in parts { if i > 255u { fail "Invalid IP Address part."; } }
ipv4(parts[0] as u8, parts[1] as u8, parts[2] as u8, parts[3] as u8)
}