Rust网络编程(2)-IpAddr和SocketAddr使用

IpAddr和SocketAddr使用

1. IpAddr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use std::net::{IpAddr,Ipv4Addr,Ipv6Addr};
fn main() {
let v4 = IpAddr::V4(Ipv4Addr::new(127,0,0,1));
let v6 = IpAddr::V6(Ipv6Addr::new(0,0,0,0,0,0,0,1));
assert_eq!("127.0.0.1".parse(),Ok(v4));
assert_eq!("::1".parse(),Ok(v6));

assert_eq!(v4.is_loopback(),true);
assert_eq!(v6.is_loopback(),true);
assert_eq!(IpAddr::V4(Ipv4Addr::new(192,168,0,1)).is_loopback(),false);

assert_eq!(v4.is_multicast(),false);
assert_eq!(v6.is_multicast(),false);
assert_eq!(IpAddr::V4(Ipv4Addr::new(224,254,0,0)).is_multicast(),true);

assert_eq!(v4.is_ipv4(),true);
assert_eq!(v6.is_ipv6(),true);
}

2. SocketAddr

SocketAddr和IpAddr区别:需要绑定端口才能运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
fn main() {
let mut v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127,0,0,1)),8080);
let mut v6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0,0,0,0,0,65535,0,1)),8080);

assert_eq!(v4.ip(),IpAddr::V4(Ipv4Addr::new(127,0,0,1)));

v4.set_ip(IpAddr::V4(Ipv4Addr::new(192,168,0,1)));
v6.set_ip(IpAddr::V6(Ipv6Addr::new(0,0,0,0,0,65535,0,1)));

assert_eq!(v4.ip(),IpAddr::V4(Ipv4Addr::new(192,168,0,1)));
assert_eq!(v4.port(),8080);

v4.set_port(1025);
v6.set_port(1025);

assert_eq!(v4.is_ipv4(),true);
assert_eq!(v6.is_ipv4(),false);

assert_eq!(v4.is_ipv6(),false);
assert_eq!(v6.is_ipv6(),true);
}

总结

本文编辑完毕

  • Copyrights © 2017-2023 Jason
  • Visitors: | Views:

谢谢打赏~

微信