Skip to content

Commit 3a8b7ed

Browse files
authored
Add example to create SockAddr from libc::sockaddr_storage (#615)
1 parent b54e2e6 commit 3a8b7ed

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/sockaddr.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,23 @@ impl SockAddrStorage {
4949
/// # Safety
5050
///
5151
/// The type `T` must be one of the `sockaddr_*` types defined by this platform.
52+
///
53+
/// # Examples
54+
/// ```
55+
/// # #[allow(dead_code)]
56+
/// # #[cfg(unix)] mod unix_example {
57+
/// # use core::mem::size_of;
58+
/// use libc::sockaddr_storage;
59+
/// use socket2::{SockAddr, SockAddrStorage, socklen_t};
60+
///
61+
/// fn from_sockaddr_storage(recv_address: &sockaddr_storage) -> SockAddr {
62+
/// let mut storage = SockAddrStorage::zeroed();
63+
/// let libc_address = unsafe { storage.view_as::<sockaddr_storage>() };
64+
/// *libc_address = *recv_address;
65+
/// unsafe { SockAddr::new(storage, size_of::<sockaddr_storage>() as socklen_t) }
66+
/// }
67+
/// # }
68+
/// ```
5269
#[inline]
5370
pub unsafe fn view_as<T>(&mut self) -> &mut T {
5471
assert!(size_of::<T>() <= size_of::<Self>());

0 commit comments

Comments
 (0)