1 use crate::sys::unix::net::{new_ip_socket, socket_addr};
2
3 use std::io;
4 use std::mem;
5 use std::net::{self, SocketAddr};
6 use std::os::unix::io::{AsRawFd, FromRawFd};
7
bind(addr: SocketAddr) -> io::Result<net::UdpSocket>8 pub fn bind(addr: SocketAddr) -> io::Result<net::UdpSocket> {
9 // Gives a warning for non Apple platforms.
10 #[allow(clippy::let_and_return)]
11 let socket = new_ip_socket(addr, libc::SOCK_DGRAM);
12
13 socket.and_then(|socket| {
14 let (raw_addr, raw_addr_length) = socket_addr(&addr);
15 syscall!(bind(socket, raw_addr.as_ptr(), raw_addr_length))
16 .map_err(|err| {
17 // Close the socket if we hit an error, ignoring the error
18 // from closing since we can't pass back two errors.
19 let _ = unsafe { libc::close(socket) };
20 err
21 })
22 .map(|_| unsafe { net::UdpSocket::from_raw_fd(socket) })
23 })
24 }
25
only_v6(socket: &net::UdpSocket) -> io::Result<bool>26 pub(crate) fn only_v6(socket: &net::UdpSocket) -> io::Result<bool> {
27 let mut optval: libc::c_int = 0;
28 let mut optlen = mem::size_of::<libc::c_int>() as libc::socklen_t;
29
30 syscall!(getsockopt(
31 socket.as_raw_fd(),
32 libc::IPPROTO_IPV6,
33 libc::IPV6_V6ONLY,
34 &mut optval as *mut _ as *mut _,
35 &mut optlen,
36 ))?;
37
38 Ok(optval != 0)
39 }
40