Crates.io | os_socketaddr |
lib.rs | os_socketaddr |
version | 0.2.5 |
source | src |
created_at | 2018-04-28 18:36:11.909507 |
updated_at | 2023-06-26 19:11:57.318662 |
description | A type for handling platform-native socket addresses (struct sockaddr) |
homepage | |
repository | https://github.com/a-ba/os_socketaddr |
max_upload_size | |
id | 62893 |
size | 32,563 |
This crate provides a type that can act as a platform-native socket address
(i.e. libc::sockaddr
)
The std crate provides SocketAddr
for managing socket addresses. However there is no easy way to
convert SocketAddr
from/into a libc::sockaddr
because SocketAddr
has a different internal
layout.
This crate provides OsSocketAddr
which holds a libc::sockaddr
(containing an IPv4 or IPv6
address) and the conversion functions:
SocketAddr
(*const sockaddr, socklen_t)
(*mut sockaddr, *mut socklen_t)
#[cfg(target_os="xxxxxx")]
linux
, macos
and windows
are officially supported and
actively tested.
android
, dragonfly
, emscripten
, freebsd
, fuchsia
, haiku
, hermit
, illumos
, ios
,
l4re
, netbsd
, openbsd
, redox
, solaris
, vxworks
and watchos
should work but are not
tested.
extern crate libc;
extern crate os_socketaddr;
use std::net::SocketAddr;
use libc::{c_int, c_void, size_t, ssize_t};
use os_socketaddr::OsSocketAddr;
fn sendto(socket: c_int, payload: &[u8], dst: SocketAddr) -> ssize_t
{
let addr : OsSocketAddr = dst.into();
unsafe {
libc::sendto(socket, payload.as_ptr() as *const c_void, payload.len() as size_t, 0,
addr.as_ptr(), addr.len())
}
}
fn recvfrom(socket: c_int, payload: &mut[u8]) -> (ssize_t, Option<SocketAddr>)
{
let mut addr = OsSocketAddr::new();
let mut addrlen = addr.capacity();
let nb = unsafe {
libc::recvfrom(socket, payload.as_mut_ptr() as *mut c_void, payload.len(), 0,
addr.as_mut_ptr(), &mut addrlen as *mut _)
};
(nb, addr.into())
}