Skip to content

Commit 158b134

Browse files
conectadorainliu
authored andcommitted
fix linux ipv6 handling
1 parent 2c189d6 commit 158b134

File tree

2 files changed

+7
-51
lines changed

2 files changed

+7
-51
lines changed

util/src/ifaces/ffi/unix/mod.rs

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -100,33 +100,13 @@ pub fn nix_socketaddr_to_sockaddr(sa: *mut nix::sys::socket::sockaddr) -> Option
100100
let sa: *const nix::sys::socket::sockaddr_in = sa as *const nix::libc::sockaddr_in;
101101
let sa = &unsafe { *sa };
102102
let (addr, port) = (sa.sin_addr.s_addr, sa.sin_port);
103-
(
104-
IpAddr::V4(net::Ipv4Addr::new(
105-
(addr & 0x000000FF) as u8,
106-
((addr & 0x0000FF00) >> 8) as u8,
107-
((addr & 0x00FF0000) >> 16) as u8,
108-
((addr & 0xFF000000) >> 24) as u8,
109-
)),
110-
port,
111-
)
103+
(IpAddr::V4(Into::into(u32::from_be(addr))), port)
112104
}
113105
AF_INET6 => {
114106
let sa: *const nix::sys::socket::sockaddr_in6 = sa as *const nix::libc::sockaddr_in6;
115107
let sa = &unsafe { *sa };
116108
let (addr, port) = (sa.sin6_addr.s6_addr, sa.sin6_port);
117-
(
118-
IpAddr::V6(net::Ipv6Addr::new(
119-
addr[0] as u16,
120-
addr[1] as u16,
121-
addr[2] as u16,
122-
addr[3] as u16,
123-
addr[4] as u16,
124-
addr[5] as u16,
125-
addr[6] as u16,
126-
addr[7] as u16,
127-
)),
128-
port,
129-
)
109+
(Into::into(addr), port)
130110
}
131111
_ => return None,
132112
};

util/src/vnet/interface.rs

Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -28,35 +28,11 @@ impl Interface {
2828
}
2929

3030
pub fn convert(addr: SocketAddr, mask: Option<SocketAddr>) -> Result<IpNet> {
31-
let prefix = if let Some(mask) = mask {
32-
match (addr, mask) {
33-
(SocketAddr::V4(_), SocketAddr::V4(mask)) => {
34-
let octets = mask.ip().octets();
35-
let mut prefix = 0;
36-
for octet in &octets {
37-
for i in 0..8 {
38-
prefix += (*octet >> (7 - i)) & 0x1;
39-
}
40-
}
41-
prefix
42-
}
43-
(SocketAddr::V6(_), SocketAddr::V6(mask)) => {
44-
let octets = mask.ip().octets();
45-
let mut prefix = 0;
46-
for octet in &octets {
47-
for i in 0..8 {
48-
prefix += (*octet >> (7 - i)) & 0x1;
49-
}
50-
}
51-
prefix
52-
}
53-
_ => return Err(Error::ErrInvalidMask),
54-
}
31+
if let Some(mask) = mask {
32+
Ok(IpNet::with_netmask(addr.ip(), mask.ip()).map_err(|_| Error::ErrInvalidMask)?)
5533
} else {
56-
32
57-
};
58-
let s = format!("{}/{}", addr.ip(), prefix);
59-
60-
Ok(IpNet::from_str(&s)?)
34+
Ok(IpNet::new(addr.ip(), if addr.is_ipv4() { 32 } else { 128 })
35+
.expect("ipv4 should always work with prefix 32 and ipv6 with prefix 128"))
36+
}
6137
}
6238
}

0 commit comments

Comments
 (0)