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         let ptr: *const SocketAddrLibC = self;
28         ptr.cast::<sockaddr>()
29     }
30 }
31 
socket_addr_trans(addr: &SocketAddr) -> (SocketAddrLibC, socklen_t)32 pub(crate) fn socket_addr_trans(addr: &SocketAddr) -> (SocketAddrLibC, socklen_t) {
33     match addr {
34         SocketAddr::V4(ref addr) => {
35             let sockaddr_in = libc::sockaddr_in {
36                 sin_family: libc::AF_INET as libc::sa_family_t,
37                 sin_port: addr.port().to_be(),
38                 sin_addr: libc::in_addr {
39                     s_addr: u32::from_ne_bytes(addr.ip().octets()),
40                 },
41                 sin_zero: [0; 8],
42                 #[cfg(target_os = "macos")]
43                 sin_len: 0,
44             };
45 
46             (
47                 SocketAddrLibC { v4: sockaddr_in },
48                 size_of::<libc::sockaddr_in>() as socklen_t,
49             )
50         }
51 
52         SocketAddr::V6(ref addr) => {
53             let sin6_addr = libc::in6_addr {
54                 s6_addr: addr.ip().octets(),
55             };
56 
57             let sockaddr_in6 = libc::sockaddr_in6 {
58                 sin6_family: libc::AF_INET6 as libc::sa_family_t,
59                 sin6_port: addr.port().to_be(),
60                 sin6_addr,
61                 sin6_flowinfo: addr.flowinfo(),
62                 sin6_scope_id: addr.scope_id(),
63                 #[cfg(target_os = "macos")]
64                 sin6_len: 0,
65             };
66 
67             (
68                 SocketAddrLibC { v6: sockaddr_in6 },
69                 size_of::<libc::sockaddr_in6>() as socklen_t,
70             )
71         }
72     }
73 }
74