Skip to content

Commit 17f4593

Browse files
authored
Merge pull request #1536 from swsnr/1535-safely-convert-to-ipaddr
Safely and correctly convert InetAddress to IpAddr
2 parents c665880 + 534c5d3 commit 17f4593

File tree

1 file changed

+28
-11
lines changed

1 file changed

+28
-11
lines changed

gio/src/inet_address.rs

+28-11
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Take a look at the license at the top of the repository in the LICENSE file.
22

3-
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
3+
use std::net::IpAddr;
44

55
use glib::{prelude::*, translate::*};
66

@@ -80,16 +80,33 @@ impl From<IpAddr> for InetAddress {
8080

8181
impl From<InetAddress> for IpAddr {
8282
fn from(addr: InetAddress) -> Self {
83-
let size = addr.native_size();
84-
unsafe {
85-
let bytes = ffi::g_inet_address_to_bytes(addr.to_glib_none().0);
86-
if size == 4 {
87-
Self::V4(Ipv4Addr::from(*(bytes as *const [u8; 4])))
88-
} else if size == 16 {
89-
Self::V6(Ipv6Addr::from(*(bytes as *const [u16; 8])))
90-
} else {
91-
panic!("Unknown IP kind");
92-
}
83+
match addr.to_bytes() {
84+
Some(InetAddressBytes::V4(bytes)) => IpAddr::from(*bytes),
85+
Some(InetAddressBytes::V6(bytes)) => IpAddr::from(*bytes),
86+
None => panic!("Unknown IP kind"),
9387
}
9488
}
9589
}
90+
91+
#[cfg(test)]
92+
mod tests {
93+
use std::net::IpAddr;
94+
95+
use crate::InetAddress;
96+
97+
#[test]
98+
fn test_ipv6_to_rust() {
99+
let rust_addr = "2606:50c0:8000::153".parse::<IpAddr>().unwrap();
100+
assert!(rust_addr.is_ipv6());
101+
let gio_addr = InetAddress::from(rust_addr);
102+
assert_eq!(rust_addr, IpAddr::from(gio_addr));
103+
}
104+
105+
#[test]
106+
fn test_ipv4_to_rust() {
107+
let rust_addr = "185.199.108.153".parse::<IpAddr>().unwrap();
108+
assert!(rust_addr.is_ipv4());
109+
let gio_addr = InetAddress::from(rust_addr);
110+
assert_eq!(rust_addr, IpAddr::from(gio_addr));
111+
}
112+
}

0 commit comments

Comments
 (0)