IpAddr

  1. use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
  2. // pub enum IPAddr {
  3. // V4(Ipv4Addr),
  4. // V6(Ipv6Addr)
  5. // }
  6. fn main() {
  7. let v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
  8. let v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
  9. assert_eq!(Ok(v4), "127.0.0.1".parse());
  10. assert_eq!(Ok(v6), "::1".parse());
  11. assert!(v4.is_loopback());
  12. assert!(v6.is_loopback());
  13. assert!(!IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)).is_loopback());
  14. assert_eq!(v4.is_multicast(), false);
  15. assert_eq!(v6.is_multicast(), false);
  16. assert!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast());
  17. assert!(v4.is_ipv4());
  18. assert!(v6.is_ipv6());
  19. }

SocketAddr

  1. use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
  2. fn main() {
  3. let mut v4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
  4. let v6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8000);
  5. assert_eq!(v4.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
  6. v4.set_ip(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)));
  7. assert_eq!(v4.ip(), IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)));
  8. assert_eq!(v4.port(), 8080);
  9. v4.set_port(8031);
  10. assert!(v4.is_ipv4());
  11. assert!(v6.is_ipv6());
  12. }