Skip to content

Commit 09f54f2

Browse files
committed
Get rid of mem::transmute in favor of correctly init values
1 parent 738612a commit 09f54f2

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

src/sockaddr.rs

+20-10
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,16 @@ use libc::{
99
socklen_t, AF_INET, AF_INET6,
1010
};
1111
#[cfg(windows)]
12-
use winapi::shared::in6addr::IN6_ADDR as in6_addr;
12+
use winapi::shared::in6addr::{in6_addr_u, IN6_ADDR as in6_addr};
1313
#[cfg(windows)]
14-
use winapi::shared::inaddr::IN_ADDR as in_addr;
14+
use winapi::shared::inaddr::{in_addr_S_un, IN_ADDR as in_addr};
1515
#[cfg(windows)]
1616
use winapi::shared::ws2def::{
1717
ADDRESS_FAMILY as sa_family_t, AF_INET, AF_INET6, SOCKADDR as sockaddr,
1818
SOCKADDR_IN as sockaddr_in, SOCKADDR_STORAGE as sockaddr_storage,
1919
};
2020
#[cfg(windows)]
21-
use winapi::shared::ws2ipdef::SOCKADDR_IN6_LH as sockaddr_in6;
21+
use winapi::shared::ws2ipdef::{SOCKADDR_IN6_LH_u, SOCKADDR_IN6_LH as sockaddr_in6};
2222
#[cfg(windows)]
2323
use winapi::um::ws2tcpip::socklen_t;
2424

@@ -208,8 +208,10 @@ impl From<SocketAddrV4> for SockAddr {
208208
s_addr: u32::from_ne_bytes(addr.ip().octets()),
209209
};
210210
#[cfg(windows)]
211-
let sin_addr = in_addr {
212-
S_un: unsafe { mem::transmute(u32::from_ne_bytes(addr.ip().octets())) },
211+
let sin_addr = unsafe {
212+
let mut s_un = mem::zeroed::<in_addr_S_un>();
213+
*s_un.S_addr_mut() = u32::from_ne_bytes(addr.ip().octets());
214+
in_addr { S_un: s_un }
213215
};
214216
*sockaddr_in = sockaddr_in {
215217
sin_family: AF_INET as sa_family_t,
@@ -229,14 +231,22 @@ impl From<SocketAddrV6> for SockAddr {
229231
let mut storage = MaybeUninit::<sockaddr_storage>::uninit();
230232
let sockaddr_in6 = unsafe { &mut *(storage.as_mut_ptr() as *mut sockaddr_in6) };
231233

232-
#[cfg(windows)]
233-
let sin6_addr = in6_addr {
234-
u: unsafe { mem::transmute(addr.ip().octets()) },
235-
};
236234
#[cfg(unix)]
237235
let sin6_addr = in6_addr {
238236
s6_addr: addr.ip().octets(),
239237
};
238+
#[cfg(windows)]
239+
let sin6_addr = unsafe {
240+
let mut u = mem::zeroed::<in6_addr_u>();
241+
*u.Byte_mut() = addr.ip().octets();
242+
in6_addr { u }
243+
};
244+
#[cfg(windows)]
245+
let u = unsafe {
246+
let mut u = mem::zeroed::<SOCKADDR_IN6_LH_u>();
247+
*u.sin6_scope_id_mut() = addr.scope_id();
248+
u
249+
};
240250
*sockaddr_in6 = sockaddr_in6 {
241251
sin6_family: AF_INET6 as sa_family_t,
242252
sin6_port: addr.port().to_be(),
@@ -245,7 +255,7 @@ impl From<SocketAddrV6> for SockAddr {
245255
#[cfg(unix)]
246256
sin6_scope_id: addr.scope_id(),
247257
#[cfg(windows)]
248-
u: unsafe { mem::transmute(addr.scope_id()) },
258+
u,
249259
..unsafe { mem::zeroed() }
250260
};
251261
SockAddr {

0 commit comments

Comments
 (0)