5 use crate::ffi::CString;
7 use crate::io::{self, ErrorKind, IoSlice, IoSliceMut};
9 use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
11 use crate::sys::net::netc as c;
12 use crate::sys::net::{cvt, cvt_gai, cvt_r, init, wrlen_t, Socket};
13 use crate::sys_common::{FromInner, IntoInner};
14 use crate::time::Duration;
16 use libc::{c_int, c_void};
20 target_os = "dragonfly", target_os = "freebsd",
21 target_os = "ios", target_os = "macos", target_os = "watchos",
22 target_os = "openbsd", target_os = "netbsd", target_os = "illumos",
23 target_os = "solaris", target_os = "haiku", target_os = "l4re"))] {
24 use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
25 use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
27 use crate::sys::net::netc::IPV6_ADD_MEMBERSHIP;
28 use crate::sys::net::netc::IPV6_DROP_MEMBERSHIP;
34 target_os = "linux", target_os = "android",
35 target_os = "dragonfly", target_os = "freebsd",
36 target_os = "openbsd", target_os = "netbsd",
37 target_os = "haiku"))] {
38 use libc::MSG_NOSIGNAL;
40 const MSG_NOSIGNAL: c_int = 0x0;
46 target_os = "dragonfly", target_os = "freebsd",
47 target_os = "openbsd", target_os = "netbsd",
48 target_os = "solaris", target_os = "illumos"))] {
50 type IpV4MultiCastType = c_uchar;
52 type IpV4MultiCastType = c_int;
56 ////////////////////////////////////////////////////////////////////////////////
57 // sockaddr and misc bindings
58 ////////////////////////////////////////////////////////////////////////////////
71 &option_value as *const T as *const _,
72 mem::size_of::<T>() as c::socklen_t,
78 pub fn getsockopt<T: Copy>(sock: &Socket, level: c_int, option_name: c_int) -> io::Result<T> {
80 let mut option_value: T = mem::zeroed();
81 let mut option_len = mem::size_of::<T>() as c::socklen_t;
86 &mut option_value as *mut T as *mut _,
93 fn sockname<F>(f: F) -> io::Result<SocketAddr>
95 F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int,
98 let mut storage: c::sockaddr_storage = mem::zeroed();
99 let mut len = mem::size_of_val(&storage) as c::socklen_t;
100 cvt(f(&mut storage as *mut _ as *mut _, &mut len))?;
101 sockaddr_to_addr(&storage, len as usize)
105 pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result<SocketAddr> {
106 match storage.ss_family as c_int {
108 assert!(len as usize >= mem::size_of::<c::sockaddr_in>());
109 Ok(SocketAddr::V4(FromInner::from_inner(unsafe {
110 *(storage as *const _ as *const c::sockaddr_in)
114 assert!(len as usize >= mem::size_of::<c::sockaddr_in6>());
115 Ok(SocketAddr::V6(FromInner::from_inner(unsafe {
116 *(storage as *const _ as *const c::sockaddr_in6)
119 _ => Err(io::const_io_error!(ErrorKind::InvalidInput, "invalid argument")),
123 #[cfg(target_os = "android")]
124 fn to_ipv6mr_interface(value: u32) -> c_int {
128 #[cfg(not(target_os = "android"))]
129 fn to_ipv6mr_interface(value: u32) -> libc::c_uint {
130 value as libc::c_uint
133 ////////////////////////////////////////////////////////////////////////////////
134 // get_host_addresses
135 ////////////////////////////////////////////////////////////////////////////////
137 pub struct LookupHost {
138 original: *mut c::addrinfo,
139 cur: *mut c::addrinfo,
144 pub fn port(&self) -> u16 {
149 impl Iterator for LookupHost {
150 type Item = SocketAddr;
151 fn next(&mut self) -> Option<SocketAddr> {
154 let cur = self.cur.as_ref()?;
155 self.cur = cur.ai_next;
156 match sockaddr_to_addr(mem::transmute(cur.ai_addr), cur.ai_addrlen as usize) {
157 Ok(addr) => return Some(addr),
165 unsafe impl Sync for LookupHost {}
166 unsafe impl Send for LookupHost {}
168 impl Drop for LookupHost {
170 unsafe { c::freeaddrinfo(self.original) }
174 impl TryFrom<&str> for LookupHost {
175 type Error = io::Error;
177 fn try_from(s: &str) -> io::Result<LookupHost> {
178 macro_rules! try_opt {
179 ($e:expr, $msg:expr) => {
182 None => return Err(io::const_io_error!(io::ErrorKind::InvalidInput, $msg)),
187 // split the string by ':' and convert the second part to u16
188 let (host, port_str) = try_opt!(s.rsplit_once(':'), "invalid socket address");
189 let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
190 (host, port).try_into()
194 impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
195 type Error = io::Error;
197 fn try_from((host, port): (&'a str, u16)) -> io::Result<LookupHost> {
200 let c_host = CString::new(host)?;
201 let mut hints: c::addrinfo = unsafe { mem::zeroed() };
202 hints.ai_socktype = c::SOCK_STREAM;
203 let mut res = ptr::null_mut();
205 cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res))
206 .map(|_| LookupHost { original: res, cur: res, port })
211 ////////////////////////////////////////////////////////////////////////////////
213 ////////////////////////////////////////////////////////////////////////////////
215 pub struct TcpStream {
220 pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
225 let sock = Socket::new(addr, c::SOCK_STREAM)?;
227 let (addr, len) = addr.into_inner();
228 cvt_r(|| unsafe { c::connect(sock.as_raw(), addr.as_ptr(), len) })?;
229 Ok(TcpStream { inner: sock })
232 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
235 let sock = Socket::new(addr, c::SOCK_STREAM)?;
236 sock.connect_timeout(addr, timeout)?;
237 Ok(TcpStream { inner: sock })
240 pub fn socket(&self) -> &Socket {
244 pub fn into_socket(self) -> Socket {
248 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
249 self.inner.set_timeout(dur, c::SO_RCVTIMEO)
252 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
253 self.inner.set_timeout(dur, c::SO_SNDTIMEO)
256 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
257 self.inner.timeout(c::SO_RCVTIMEO)
260 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
261 self.inner.timeout(c::SO_SNDTIMEO)
264 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
268 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
272 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
273 self.inner.read_vectored(bufs)
277 pub fn is_read_vectored(&self) -> bool {
278 self.inner.is_read_vectored()
281 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
282 let len = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
283 let ret = cvt(unsafe {
284 c::send(self.inner.as_raw(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL)
289 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
290 self.inner.write_vectored(bufs)
294 pub fn is_write_vectored(&self) -> bool {
295 self.inner.is_write_vectored()
298 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
299 sockname(|buf, len| unsafe { c::getpeername(self.inner.as_raw(), buf, len) })
302 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
303 sockname(|buf, len| unsafe { c::getsockname(self.inner.as_raw(), buf, len) })
306 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
307 self.inner.shutdown(how)
310 pub fn duplicate(&self) -> io::Result<TcpStream> {
311 self.inner.duplicate().map(|s| TcpStream { inner: s })
314 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
315 self.inner.set_linger(linger)
318 pub fn linger(&self) -> io::Result<Option<Duration>> {
322 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
323 self.inner.set_nodelay(nodelay)
326 pub fn nodelay(&self) -> io::Result<bool> {
330 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
331 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
334 pub fn ttl(&self) -> io::Result<u32> {
335 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
339 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
340 self.inner.take_error()
343 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
344 self.inner.set_nonblocking(nonblocking)
348 impl FromInner<Socket> for TcpStream {
349 fn from_inner(socket: Socket) -> TcpStream {
350 TcpStream { inner: socket }
354 impl fmt::Debug for TcpStream {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 let mut res = f.debug_struct("TcpStream");
358 if let Ok(addr) = self.socket_addr() {
359 res.field("addr", &addr);
362 if let Ok(peer) = self.peer_addr() {
363 res.field("peer", &peer);
366 let name = if cfg!(windows) { "socket" } else { "fd" };
367 res.field(name, &self.inner.as_raw()).finish()
371 ////////////////////////////////////////////////////////////////////////////////
373 ////////////////////////////////////////////////////////////////////////////////
375 pub struct TcpListener {
380 pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result<TcpListener> {
385 let sock = Socket::new(addr, c::SOCK_STREAM)?;
387 // On platforms with Berkeley-derived sockets, this allows to quickly
388 // rebind a socket, without needing to wait for the OS to clean up the
391 // On Windows, this allows rebinding sockets which are actively in use,
392 // which allows “socket hijacking”, so we explicitly don't set it here.
393 // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
395 setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?;
397 // Bind our new socket
398 let (addr, len) = addr.into_inner();
399 cvt(unsafe { c::bind(sock.as_raw(), addr.as_ptr(), len as _) })?;
402 if #[cfg(target_os = "horizon")] {
403 // The 3DS doesn't support a big connection backlog. Sometimes
404 // it allows up to about 37, but other times it doesn't even
405 // accept 32. There may be a global limitation causing this.
408 // The default for all other platforms
414 cvt(unsafe { c::listen(sock.as_raw(), backlog) })?;
415 Ok(TcpListener { inner: sock })
418 pub fn socket(&self) -> &Socket {
422 pub fn into_socket(self) -> Socket {
426 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
427 sockname(|buf, len| unsafe { c::getsockname(self.inner.as_raw(), buf, len) })
430 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
431 let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
432 let mut len = mem::size_of_val(&storage) as c::socklen_t;
433 let sock = self.inner.accept(&mut storage as *mut _ as *mut _, &mut len)?;
434 let addr = sockaddr_to_addr(&storage, len as usize)?;
435 Ok((TcpStream { inner: sock }, addr))
438 pub fn duplicate(&self) -> io::Result<TcpListener> {
439 self.inner.duplicate().map(|s| TcpListener { inner: s })
442 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
443 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
446 pub fn ttl(&self) -> io::Result<u32> {
447 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
451 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
452 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
455 pub fn only_v6(&self) -> io::Result<bool> {
456 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY)?;
460 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
461 self.inner.take_error()
464 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
465 self.inner.set_nonblocking(nonblocking)
469 impl FromInner<Socket> for TcpListener {
470 fn from_inner(socket: Socket) -> TcpListener {
471 TcpListener { inner: socket }
475 impl fmt::Debug for TcpListener {
476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477 let mut res = f.debug_struct("TcpListener");
479 if let Ok(addr) = self.socket_addr() {
480 res.field("addr", &addr);
483 let name = if cfg!(windows) { "socket" } else { "fd" };
484 res.field(name, &self.inner.as_raw()).finish()
488 ////////////////////////////////////////////////////////////////////////////////
490 ////////////////////////////////////////////////////////////////////////////////
492 pub struct UdpSocket {
497 pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
502 let sock = Socket::new(addr, c::SOCK_DGRAM)?;
503 let (addr, len) = addr.into_inner();
504 cvt(unsafe { c::bind(sock.as_raw(), addr.as_ptr(), len as _) })?;
505 Ok(UdpSocket { inner: sock })
508 pub fn socket(&self) -> &Socket {
512 pub fn into_socket(self) -> Socket {
516 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
517 sockname(|buf, len| unsafe { c::getpeername(self.inner.as_raw(), buf, len) })
520 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
521 sockname(|buf, len| unsafe { c::getsockname(self.inner.as_raw(), buf, len) })
524 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
525 self.inner.recv_from(buf)
528 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
529 self.inner.peek_from(buf)
532 pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
533 let len = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
534 let (dst, dstlen) = dst.into_inner();
535 let ret = cvt(unsafe {
538 buf.as_ptr() as *const c_void,
548 pub fn duplicate(&self) -> io::Result<UdpSocket> {
549 self.inner.duplicate().map(|s| UdpSocket { inner: s })
552 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
553 self.inner.set_timeout(dur, c::SO_RCVTIMEO)
556 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
557 self.inner.set_timeout(dur, c::SO_SNDTIMEO)
560 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
561 self.inner.timeout(c::SO_RCVTIMEO)
564 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
565 self.inner.timeout(c::SO_SNDTIMEO)
568 pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
569 setsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST, broadcast as c_int)
572 pub fn broadcast(&self) -> io::Result<bool> {
573 let raw: c_int = getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST)?;
577 pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
581 c::IP_MULTICAST_LOOP,
582 multicast_loop_v4 as IpV4MultiCastType,
586 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
587 let raw: IpV4MultiCastType = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP)?;
591 pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
596 multicast_ttl_v4 as IpV4MultiCastType,
600 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
601 let raw: IpV4MultiCastType = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL)?;
605 pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
606 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP, multicast_loop_v6 as c_int)
609 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
610 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP)?;
614 pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
615 let mreq = c::ip_mreq {
616 imr_multiaddr: multiaddr.into_inner(),
617 imr_interface: interface.into_inner(),
619 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq)
622 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
623 let mreq = c::ipv6_mreq {
624 ipv6mr_multiaddr: multiaddr.into_inner(),
625 ipv6mr_interface: to_ipv6mr_interface(interface),
627 setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq)
630 pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
631 let mreq = c::ip_mreq {
632 imr_multiaddr: multiaddr.into_inner(),
633 imr_interface: interface.into_inner(),
635 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq)
638 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
639 let mreq = c::ipv6_mreq {
640 ipv6mr_multiaddr: multiaddr.into_inner(),
641 ipv6mr_interface: to_ipv6mr_interface(interface),
643 setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq)
646 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
647 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
650 pub fn ttl(&self) -> io::Result<u32> {
651 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
655 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
656 self.inner.take_error()
659 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
660 self.inner.set_nonblocking(nonblocking)
663 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
667 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
671 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
672 let len = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
673 let ret = cvt(unsafe {
674 c::send(self.inner.as_raw(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL)
679 pub fn connect(&self, addr: io::Result<&SocketAddr>) -> io::Result<()> {
680 let (addr, len) = addr?.into_inner();
681 cvt_r(|| unsafe { c::connect(self.inner.as_raw(), addr.as_ptr(), len) }).map(drop)
685 impl FromInner<Socket> for UdpSocket {
686 fn from_inner(socket: Socket) -> UdpSocket {
687 UdpSocket { inner: socket }
691 impl fmt::Debug for UdpSocket {
692 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693 let mut res = f.debug_struct("UdpSocket");
695 if let Ok(addr) = self.socket_addr() {
696 res.field("addr", &addr);
699 let name = if cfg!(windows) { "socket" } else { "fd" };
700 res.field(name, &self.inner.as_raw()).finish()
704 ////////////////////////////////////////////////////////////////////////////////
705 // Converting SocketAddr to libc representation
706 ////////////////////////////////////////////////////////////////////////////////
708 /// A type with the same memory layout as `c::sockaddr`. Used in converting Rust level
709 /// SocketAddr* types into their system representation. The benefit of this specific
710 /// type over using `c::sockaddr_storage` is that this type is exactly as large as it
711 /// needs to be and not a lot larger. And it can be initialized more cleanly from Rust.
713 pub(crate) union SocketAddrCRepr {
718 impl SocketAddrCRepr {
719 pub fn as_ptr(&self) -> *const c::sockaddr {
720 self as *const _ as *const c::sockaddr
724 impl<'a> IntoInner<(SocketAddrCRepr, c::socklen_t)> for &'a SocketAddr {
725 fn into_inner(self) -> (SocketAddrCRepr, c::socklen_t) {
727 SocketAddr::V4(ref a) => {
728 let sockaddr = SocketAddrCRepr { v4: a.into_inner() };
729 (sockaddr, mem::size_of::<c::sockaddr_in>() as c::socklen_t)
731 SocketAddr::V6(ref a) => {
732 let sockaddr = SocketAddrCRepr { v6: a.into_inner() };
733 (sockaddr, mem::size_of::<c::sockaddr_in6>() as c::socklen_t)