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::{AsInner, 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",
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 (addrp, len) = addr.into_inner();
228 cvt_r(|| unsafe { c::connect(sock.as_raw(), addrp, 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 (addrp, len) = addr.into_inner();
399 cvt(unsafe { c::bind(sock.as_raw(), addrp, len as _) })?;
402 #[cfg(not(target_os = "horizon"))]
403 cvt(unsafe { c::listen(sock.as_raw(), 128) })?;
404 // 40 is the maximum for Horizon OS
405 #[cfg(target_os = "horizon")]
406 cvt(unsafe { c::listen(sock.as_raw(), 40) })?;
408 Ok(TcpListener { inner: sock })
411 pub fn socket(&self) -> &Socket {
415 pub fn into_socket(self) -> Socket {
419 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
420 sockname(|buf, len| unsafe { c::getsockname(self.inner.as_raw(), buf, len) })
423 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
424 let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
425 let mut len = mem::size_of_val(&storage) as c::socklen_t;
426 let sock = self.inner.accept(&mut storage as *mut _ as *mut _, &mut len)?;
427 let addr = sockaddr_to_addr(&storage, len as usize)?;
428 Ok((TcpStream { inner: sock }, addr))
431 pub fn duplicate(&self) -> io::Result<TcpListener> {
432 self.inner.duplicate().map(|s| TcpListener { inner: s })
435 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
436 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
439 pub fn ttl(&self) -> io::Result<u32> {
440 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
444 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
445 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
448 pub fn only_v6(&self) -> io::Result<bool> {
449 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY)?;
453 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
454 self.inner.take_error()
457 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
458 self.inner.set_nonblocking(nonblocking)
462 impl FromInner<Socket> for TcpListener {
463 fn from_inner(socket: Socket) -> TcpListener {
464 TcpListener { inner: socket }
468 impl fmt::Debug for TcpListener {
469 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
470 let mut res = f.debug_struct("TcpListener");
472 if let Ok(addr) = self.socket_addr() {
473 res.field("addr", &addr);
476 let name = if cfg!(windows) { "socket" } else { "fd" };
477 res.field(name, &self.inner.as_raw()).finish()
481 ////////////////////////////////////////////////////////////////////////////////
483 ////////////////////////////////////////////////////////////////////////////////
485 pub struct UdpSocket {
490 pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
495 let sock = Socket::new(addr, c::SOCK_DGRAM)?;
496 let (addrp, len) = addr.into_inner();
497 cvt(unsafe { c::bind(sock.as_raw(), addrp, len as _) })?;
498 Ok(UdpSocket { inner: sock })
501 pub fn socket(&self) -> &Socket {
505 pub fn into_socket(self) -> Socket {
509 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
510 sockname(|buf, len| unsafe { c::getpeername(self.inner.as_raw(), buf, len) })
513 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
514 sockname(|buf, len| unsafe { c::getsockname(self.inner.as_raw(), buf, len) })
517 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
518 self.inner.recv_from(buf)
521 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
522 self.inner.peek_from(buf)
525 pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
526 let len = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
527 let (dstp, dstlen) = dst.into_inner();
528 let ret = cvt(unsafe {
531 buf.as_ptr() as *const c_void,
541 pub fn duplicate(&self) -> io::Result<UdpSocket> {
542 self.inner.duplicate().map(|s| UdpSocket { inner: s })
545 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
546 self.inner.set_timeout(dur, c::SO_RCVTIMEO)
549 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
550 self.inner.set_timeout(dur, c::SO_SNDTIMEO)
553 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
554 self.inner.timeout(c::SO_RCVTIMEO)
557 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
558 self.inner.timeout(c::SO_SNDTIMEO)
561 pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
562 setsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST, broadcast as c_int)
565 pub fn broadcast(&self) -> io::Result<bool> {
566 let raw: c_int = getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST)?;
570 pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
574 c::IP_MULTICAST_LOOP,
575 multicast_loop_v4 as IpV4MultiCastType,
579 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
580 let raw: IpV4MultiCastType = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP)?;
584 pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
589 multicast_ttl_v4 as IpV4MultiCastType,
593 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
594 let raw: IpV4MultiCastType = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL)?;
598 pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
599 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP, multicast_loop_v6 as c_int)
602 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
603 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP)?;
607 pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
608 let mreq = c::ip_mreq {
609 imr_multiaddr: multiaddr.into_inner(),
610 imr_interface: interface.into_inner(),
612 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq)
615 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
616 let mreq = c::ipv6_mreq {
617 ipv6mr_multiaddr: *multiaddr.as_inner(),
618 ipv6mr_interface: to_ipv6mr_interface(interface),
620 setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq)
623 pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
624 let mreq = c::ip_mreq {
625 imr_multiaddr: multiaddr.into_inner(),
626 imr_interface: interface.into_inner(),
628 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq)
631 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
632 let mreq = c::ipv6_mreq {
633 ipv6mr_multiaddr: *multiaddr.as_inner(),
634 ipv6mr_interface: to_ipv6mr_interface(interface),
636 setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq)
639 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
640 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
643 pub fn ttl(&self) -> io::Result<u32> {
644 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
648 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
649 self.inner.take_error()
652 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
653 self.inner.set_nonblocking(nonblocking)
656 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
660 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
664 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
665 let len = cmp::min(buf.len(), <wrlen_t>::MAX as usize) as wrlen_t;
666 let ret = cvt(unsafe {
667 c::send(self.inner.as_raw(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL)
672 pub fn connect(&self, addr: io::Result<&SocketAddr>) -> io::Result<()> {
673 let (addrp, len) = addr?.into_inner();
674 cvt_r(|| unsafe { c::connect(self.inner.as_raw(), addrp, len) }).map(drop)
678 impl FromInner<Socket> for UdpSocket {
679 fn from_inner(socket: Socket) -> UdpSocket {
680 UdpSocket { inner: socket }
684 impl fmt::Debug for UdpSocket {
685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686 let mut res = f.debug_struct("UdpSocket");
688 if let Ok(addr) = self.socket_addr() {
689 res.field("addr", &addr);
692 let name = if cfg!(windows) { "socket" } else { "fd" };
693 res.field(name, &self.inner.as_raw()).finish()