#libc #socket #sockaddr

os_socketaddr

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

2 releases

Uses old Rust 2015

0.1.1 Nov 12, 2020
0.1.0 Apr 28, 2018

#89 in Unix APIs

Download history 91/week @ 2020-08-13 110/week @ 2020-08-20 90/week @ 2020-08-27 47/week @ 2020-09-03 128/week @ 2020-09-10 55/week @ 2020-09-17 88/week @ 2020-09-24 116/week @ 2020-10-01 119/week @ 2020-10-08 97/week @ 2020-10-15 87/week @ 2020-10-22 42/week @ 2020-10-29 61/week @ 2020-11-05 152/week @ 2020-11-12 123/week @ 2020-11-19 248/week @ 2020-11-26

378 downloads per month
Used in 2 crates (via udp_sas)

MIT/Apache

13KB
220 lines

os_socketaddr

Build Status Crates.io

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

Motivation

The std crate provides std::net::SocketAddr for managing socket addresses. Its V4 variant encapsulates a libc::sockaddr_in and its V6 variant encapsulates a libc::sockaddr_in6. However there is no easy way to convert SocketAddr from/into a libc::sockaddr, because SocketAddr is a rust enum.

This crate provides OsSocketAddr which holds a libc::sockaddr (containing an IPv4 or IPv6 address) and the conversion functions from/into std::net::SocketAddr.


lib.rs:

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

#Motivation

The std crate provides std::net::SocketAddr for managing socket addresses. Its V4 variant encapsulates a libc::sockaddr_in and its V6 variant encapsulates a libc::sockaddr_in6. However there is no easy way to convert SocketAddr from/into a libc::sockaddr, because SocketAddr is a rust enum.

This crate provides OsSocketAddr which holds a libc::sockaddr (containing an IPv4 or IPv6 address) and the conversion functions from/into std::net::SocketAddr.

#Example

# mod foo {
extern crate libc;
extern crate os_socketaddr;

use std::net::SocketAddr;
use self::libc::{c_int, c_void, size_t, ssize_t};
use self::os_socketaddr::OsSocketAddr;

fn send(socket: c_int, buf: &[u8], dst: SocketAddr) -> ssize_t {
    let addr : OsSocketAddr = dst.into();
    unsafe {
        libc::sendto(socket, buf.as_ptr() as *const c_void, buf.len() as size_t, 0,
                     addr.as_ptr(), addr.len())
    }
}

fn receive(socket: c_int, buf: &mut[u8]) -> (ssize_t, Option<SocketAddr>)
{
    let mut addr = OsSocketAddr::new();
    let mut addrlen = addr.capacity();
    let nb = unsafe {
        libc::recvfrom(socket, buf.as_mut_ptr() as *mut c_void, buf.len(), 0,
                       addr.as_mut_ptr(), &mut addrlen as *mut _)
    };
    (nb, addr.into())
}
# }

Dependencies

~28KB