os_socketaddr

Crates.io License: Mit or Apache 2.0 Build Status

This crate provides a type that can act as a platform-native socket address (i.e. libc::sockaddr)

Motivation

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 from/into SocketAddr.

Supported targets   #[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.

Example

```rust extern crate libc; extern crate os_socketaddr;

use std::net::SocketAddr; use libc::{cint, cvoid, sizet, ssizet}; use os_socketaddr::OsSocketAddr;

fn sendto(socket: cint, payload: &[u8], dst: SocketAddr) -> ssizet { let addr : OsSocketAddr = dst.into(); unsafe { libc::sendto(socket, payload.asptr() as *const cvoid, payload.len() as sizet, 0, addr.asptr(), addr.len()) } }

fn recvfrom(socket: cint, payload: &mut[u8]) -> (ssizet, Option) { let mut addr = OsSocketAddr::new(); let mut addrlen = addr.capacity(); let nb = unsafe { libc::recvfrom(socket, payload.asmutptr() as *mut cvoid, payload.len(), 0, addr.asmut_ptr(), &mut addrlen as *mut _) }; (nb, addr.into()) } ```