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
57mod sealed {
58    pub trait Sealed {}
59    impl<T: super::IsA<super::InetAddress>> Sealed for T {}
60}
61
62pub trait InetAddressExtManual: sealed::Sealed + IsA<InetAddress> + 'static {
63    // rustdoc-stripper-ignore-next
64    /// Returns `None` in case the address has a native size different than 4 and 16.
65    // rustdoc-stripper-ignore-next-stop
66    /// Gets the raw binary address data from @self.
67    ///
68    /// # Returns
69    ///
70    /// a pointer to an internal array of the bytes in @self,
71    /// which should not be modified, stored, or freed. The size of this
72    /// array can be gotten with g_inet_address_get_native_size().
73    #[doc(alias = "g_inet_address_to_bytes")]
74    #[inline]
75    fn to_bytes(&self) -> Option<InetAddressBytes<'_>> {
76        let size = self.native_size();
77        unsafe {
78            let bytes = ffi::g_inet_address_to_bytes(self.as_ref().to_glib_none().0);
79            if size == 4 {
80                Some(InetAddressBytes::V4(&*(bytes as *const [u8; 4])))
81            } else if size == 16 {
82                Some(InetAddressBytes::V6(&*(bytes as *const [u8; 16])))
83            } else {
84                None
85            }
86        }
87    }
88}
89
90impl<O: IsA<InetAddress>> InetAddressExtManual for O {}
91
92impl From<IpAddr> for InetAddress {
93    fn from(addr: IpAddr) -> Self {
94        match addr {
95            IpAddr::V4(v4) => Self::from_bytes(InetAddressBytes::V4(&v4.octets())),
96            IpAddr::V6(v6) => Self::from_bytes(InetAddressBytes::V6(&v6.octets())),
97        }
98    }
99}
100
101impl From<InetAddress> for IpAddr {
102    fn from(addr: InetAddress) -> Self {
103        match addr.to_bytes() {
104            Some(InetAddressBytes::V4(bytes)) => IpAddr::from(*bytes),
105            Some(InetAddressBytes::V6(bytes)) => IpAddr::from(*bytes),
106            None => panic!("Unknown IP kind"),
107        }
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use std::net::IpAddr;
114
115    use crate::InetAddress;
116
117    #[test]
118    fn test_ipv6_to_rust() {
119        let rust_addr = "2606:50c0:8000::153".parse::<IpAddr>().unwrap();
120        assert!(rust_addr.is_ipv6());
121        let gio_addr = InetAddress::from(rust_addr);
122        assert_eq!(rust_addr, IpAddr::from(gio_addr));
123    }
124
125    #[test]
126    fn test_ipv4_to_rust() {
127        let rust_addr = "185.199.108.153".parse::<IpAddr>().unwrap();
128        assert!(rust_addr.is_ipv4());
129        let gio_addr = InetAddress::from(rust_addr);
130        assert_eq!(rust_addr, IpAddr::from(gio_addr));
131    }
132}