Eliminate some more transmute() (#8879)

* eliminate some more transmute()

* Address `review comments`

* Make unsafe block smaller
* Use different byte-order than `std`, read words as big endian instead
of little endian!

* Fix IpAddresses nits

* Use `from_be` to work both for big and little endian
* Ipv6 addresses were incorrectly `transmuted`

* remove needless lifetime annotation
This commit is contained in:
Niklas Adolfsson
2018-06-22 13:51:53 +02:00
committed by André Silva
parent 5ae8e8a9ca
commit 0cd1de769b
2 changed files with 22 additions and 31 deletions

View File

@@ -20,8 +20,8 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV
use std::io;
use igd::{PortMappingProtocol, search_gateway_from_timeout};
use std::time::Duration;
use node_table::{NodeEndpoint};
use ipnetwork::{IpNetwork};
use node_table::NodeEndpoint;
use ipnetwork::IpNetwork;
/// Socket address extension for rustc beta. To be replaces with now unstable API
pub trait SocketAddrExt {
@@ -225,28 +225,17 @@ mod getinterfaces {
let sa: *const sockaddr_in = sa as *const sockaddr_in;
let sa = unsafe { &*sa };
let (addr, port) = (sa.sin_addr.s_addr, sa.sin_port);
(IpAddr::V4(Ipv4Addr::new(
(addr & 0x0000_00FF) as u8,
((addr & 0x0000_FF00) >> 8) as u8,
((addr & 0x00FF_0000) >> 16) as u8,
((addr & 0xFF00_0000) >> 24) as u8)),
port)
// convert u32 to an `Ipv4 address`, but the u32 must be converted to `host-order`
// that's why `from_be` is used!
(IpAddr::V4(Ipv4Addr::from(<u32>::from_be(addr))), port)
},
AF_INET6 => {
let sa: *const sockaddr_in6 = sa as *const sockaddr_in6;
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin6_addr.s6_addr, sa.sin6_port);
let addr: [u16; 8] = unsafe { mem::transmute(addr) };
(IpAddr::V6(Ipv6Addr::new(
addr[0],
addr[1],
addr[2],
addr[3],
addr[4],
addr[5],
addr[6],
addr[7])),
port)
let ip_addr = Ipv6Addr::from(addr);
debug_assert!(addr == ip_addr.octets());
(IpAddr::V6(ip_addr), port)
},
_ => return None,
};