gio/
inet_address.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::net::IpAddr;
4
5use glib::{prelude::*, translate::*};
6
7use crate::{ffi, prelude::*, InetAddress, SocketFamily};
8
9#[derive(Debug)]
10pub enum InetAddressBytes<'a> {
11    V4(&'a [u8; 4]),
12    V6(&'a [u8; 16]),
13}
14
15impl InetAddressBytes<'_> {
16    #[inline]
17    fn deref(&self) -> &[u8] {
18        use self::InetAddressBytes::*;
19
20        match *self {
21            V4(bytes) => bytes,
22            V6(bytes) => bytes,
23        }
24    }
25}
26
27impl InetAddress {
28    /// Creates a new #GInetAddress from the given @family and @bytes.
29    /// @bytes should be 4 bytes for [`SocketFamily::Ipv4`][crate::SocketFamily::Ipv4] and 16 bytes for
30    /// [`SocketFamily::Ipv6`][crate::SocketFamily::Ipv6].
31    /// ## `bytes`
32    /// raw address data
33    /// ## `family`
34    /// the address family of @bytes
35    ///
36    /// # Returns
37    ///
38    /// a new #GInetAddress corresponding to @family and @bytes.
39    ///     Free the returned object with g_object_unref().
40    #[doc(alias = "g_inet_address_new_from_bytes")]
41    pub fn from_bytes(inet_address_bytes: InetAddressBytes) -> Self {
42        let bytes = inet_address_bytes.deref();
43
44        let family = match inet_address_bytes {
45            InetAddressBytes::V4(_) => SocketFamily::Ipv4,
46            InetAddressBytes::V6(_) => SocketFamily::Ipv6,
47        };
48        unsafe {
49            from_glib_full(ffi::g_inet_address_new_from_bytes(
50                bytes.to_glib_none().0,
51                family.into_glib(),
52            ))
53        }
54    }
55}
56
57pub trait InetAddressExtManual: IsA<InetAddress> + 'static {
58    // rustdoc-stripper-ignore-next
59    /// Returns `None` in case the address has a native size different than 4 and 16.
60    // rustdoc-stripper-ignore-next-stop
61    /// Gets the raw binary address data from @self.
62    ///
63    /// # Returns
64    ///
65    /// a pointer to an internal array of the bytes in @self,
66    /// which should not be modified, stored, or freed. The size of this
67    /// array can be gotten with g_inet_address_get_native_size().
68    #[doc(alias = "g_inet_address_to_bytes")]
69    #[inline]
70    fn to_bytes(&self) -> Option<InetAddressBytes<'_>> {
71        let size = self.native_size();
72        unsafe {
73            let bytes = ffi::g_inet_address_to_bytes(self.as_ref().to_glib_none().0);
74            if size == 4 {
75                Some(InetAddressBytes::V4(&*(bytes as *const [u8; 4])))
76            } else if size == 16 {
77                Some(InetAddressBytes::V6(&*(bytes as *const [u8; 16])))
78            } else {
79                None
80            }
81        }
82    }
83}
84
85impl<O: IsA<InetAddress>> InetAddressExtManual for O {}
86
87impl From<IpAddr> for InetAddress {
88    fn from(addr: IpAddr) -> Self {
89        match addr {
90            IpAddr::V4(v4) => Self::from_bytes(InetAddressBytes::V4(&v4.octets())),
91            IpAddr::V6(v6) => Self::from_bytes(InetAddressBytes::V6(&v6.octets())),
92        }
93    }
94}
95
96impl From<InetAddress> for IpAddr {
97    fn from(addr: InetAddress) -> Self {
98        match addr.to_bytes() {
99            Some(InetAddressBytes::V4(bytes)) => IpAddr::from(*bytes),
100            Some(InetAddressBytes::V6(bytes)) => IpAddr::from(*bytes),
101            None => panic!("Unknown IP kind"),
102        }
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use std::net::IpAddr;
109
110    use crate::InetAddress;
111
112    #[test]
113    fn test_ipv6_to_rust() {
114        let rust_addr = "2606:50c0:8000::153".parse::<IpAddr>().unwrap();
115        assert!(rust_addr.is_ipv6());
116        let gio_addr = InetAddress::from(rust_addr);
117        assert_eq!(rust_addr, IpAddr::from(gio_addr));
118    }
119
120    #[test]
121    fn test_ipv4_to_rust() {
122        let rust_addr = "185.199.108.153".parse::<IpAddr>().unwrap();
123        assert!(rust_addr.is_ipv4());
124        let gio_addr = InetAddress::from(rust_addr);
125        assert_eq!(rust_addr, IpAddr::from(gio_addr));
126    }
127}