#socket-address #sockets #libc #api-bindings

os_socketaddr

A type for handling platform-native socket addresses (struct sockaddr)

4 releases

0.2.5 Jun 26, 2023
0.2.4 Nov 29, 2022
0.2.3 Sep 2, 2022
0.2.2 Aug 26, 2022
0.1.0 Apr 28, 2018

#248 in Network programming

Download history 951/week @ 2024-08-14 1095/week @ 2024-08-21 1257/week @ 2024-08-28 878/week @ 2024-09-04 1875/week @ 2024-09-11 1144/week @ 2024-09-18 1256/week @ 2024-09-25 1099/week @ 2024-10-02 1445/week @ 2024-10-09 1354/week @ 2024-10-16 1694/week @ 2024-10-23 1718/week @ 2024-10-30 1648/week @ 2024-11-06 1131/week @ 2024-11-13 1593/week @ 2024-11-20 935/week @ 2024-11-27

5,729 downloads per month
Used in 25 crates (13 directly)

MIT/Apache

33KB
492 lines

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
  • from (*const sockaddr, socklen_t)
  • into (*mut sockaddr, *mut socklen_t)

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

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())
}

Dependencies

~215KB