rustix/backend/linux_raw/net/
write_sockaddr.rs

1//! The BSD sockets API requires us to read the `sa_family` field before we can
2//! interpret the rest of a `sockaddr` produced by the kernel.
3#![allow(unsafe_code)]
4
5use crate::backend::c;
6use crate::net::{SocketAddrV4, SocketAddrV6};
7
8pub(crate) fn encode_sockaddr_v4(v4: &SocketAddrV4) -> c::sockaddr_in {
9    c::sockaddr_in {
10        sin_family: c::AF_INET as _,
11        sin_port: u16::to_be(v4.port()),
12        sin_addr: c::in_addr {
13            s_addr: u32::from_ne_bytes(v4.ip().octets()),
14        },
15        __pad: [0_u8; 8],
16    }
17}
18
19pub(crate) fn encode_sockaddr_v6(v6: &SocketAddrV6) -> c::sockaddr_in6 {
20    c::sockaddr_in6 {
21        sin6_family: c::AF_INET6 as _,
22        sin6_port: u16::to_be(v6.port()),
23        sin6_flowinfo: u32::to_be(v6.flowinfo()),
24        sin6_addr: c::in6_addr {
25            in6_u: linux_raw_sys::net::in6_addr__bindgen_ty_1 {
26                u6_addr8: v6.ip().octets(),
27            },
28        },
29        sin6_scope_id: v6.scope_id(),
30    }
31}