1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 use std::mem::size_of;
15 use std::net::SocketAddr;
16
17 use libc::{sockaddr, socklen_t};
18
19 #[repr(C)]
20 pub(crate) union SocketAddrLibC {
21 v4: libc::sockaddr_in,
22 v6: libc::sockaddr_in6,
23 }
24
25 impl SocketAddrLibC {
as_ptr(&self) -> *const sockaddr26 pub(crate) fn as_ptr(&self) -> *const sockaddr {
27 self as *const _ as *const sockaddr
28 }
29 }
30
socket_addr_trans(addr: &SocketAddr) -> (SocketAddrLibC, socklen_t)31 pub(crate) fn socket_addr_trans(addr: &SocketAddr) -> (SocketAddrLibC, socklen_t) {
32 match addr {
33 SocketAddr::V4(ref addr) => {
34 let sockaddr_in = libc::sockaddr_in {
35 sin_family: libc::AF_INET as libc::sa_family_t,
36 sin_port: addr.port().to_be(),
37 sin_addr: libc::in_addr {
38 s_addr: u32::from_ne_bytes(addr.ip().octets()),
39 },
40 sin_zero: [0; 8],
41 };
42
43 (
44 SocketAddrLibC { v4: sockaddr_in },
45 size_of::<libc::sockaddr_in>() as socklen_t,
46 )
47 }
48
49 SocketAddr::V6(ref addr) => {
50 let sin6_addr = libc::in6_addr {
51 s6_addr: addr.ip().octets(),
52 };
53
54 let sockaddr_in6 = libc::sockaddr_in6 {
55 sin6_family: libc::AF_INET6 as libc::sa_family_t,
56 sin6_port: addr.port().to_be(),
57 sin6_addr,
58 sin6_flowinfo: addr.flowinfo(),
59 sin6_scope_id: addr.scope_id(),
60 };
61
62 (
63 SocketAddrLibC { v6: sockaddr_in6 },
64 size_of::<libc::sockaddr_in6>() as socklen_t,
65 )
66 }
67 }
68 }
69