Skip to content

Commit bf9299b

Browse files
committed
Add example to create SockAddr from libc::sockaddr_storage
1 parent b54e2e6 commit bf9299b

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

src/sockaddr.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,22 @@ 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 libc::sockaddr_storage;
58+
/// use socket2::{SockAddr, SockAddrStorage, socklen_t};
59+
///
60+
/// fn from_sockaddr_storage(recv_address: &sockaddr_storage) -> SockAddr {
61+
/// let mut storage = SockAddrStorage::zeroed();
62+
/// let libc_address = unsafe { storage.view_as::<sockaddr_storage>() };
63+
/// *libc_address = *recv_address;
64+
/// unsafe { SockAddr::new(storage, size_of::<sockaddr_storage>() as socklen_t) }
65+
/// }
66+
/// # }
67+
/// ```
5268
#[inline]
5369
pub unsafe fn view_as<T>(&mut self) -> &mut T {
5470
assert!(size_of::<T>() <= size_of::<Self>());

0 commit comments

Comments
 (0)