1 use crate::io::{Interest, PollEvented, ReadBuf, Ready};
2 use crate::net::{to_socket_addrs, ToSocketAddrs};
3 
4 use std::convert::TryFrom;
5 use std::fmt;
6 use std::io;
7 use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr};
8 use std::task::{Context, Poll};
9 
10 cfg_io_util! {
11     use bytes::BufMut;
12 }
13 
14 cfg_net! {
15     /// A UDP socket
16     ///
17     /// UDP is "connectionless", unlike TCP. Meaning, regardless of what address you've bound to, a `UdpSocket`
18     /// is free to communicate with many different remotes. In tokio there are basically two main ways to use `UdpSocket`:
19     ///
20     /// * one to many: [`bind`](`UdpSocket::bind`) and use [`send_to`](`UdpSocket::send_to`)
21     ///   and [`recv_from`](`UdpSocket::recv_from`) to communicate with many different addresses
22     /// * one to one: [`connect`](`UdpSocket::connect`) and associate with a single address, using [`send`](`UdpSocket::send`)
23     ///   and [`recv`](`UdpSocket::recv`) to communicate only with that remote address
24     ///
25     /// This type does not provide a `split` method, because this functionality
26     /// can be achieved by instead wrapping the socket in an [`Arc`]. Note that
27     /// you do not need a `Mutex` to share the `UdpSocket` — an `Arc<UdpSocket>`
28     /// is enough. This is because all of the methods take `&self` instead of
29     /// `&mut self`. Once you have wrapped it in an `Arc`, you can call
30     /// `.clone()` on the `Arc<UdpSocket>` to get multiple shared handles to the
31     /// same socket. An example of such usage can be found further down.
32     ///
33     /// [`Arc`]: std::sync::Arc
34     ///
35     /// # Streams
36     ///
37     /// If you need to listen over UDP and produce a [`Stream`], you can look
38     /// at [`UdpFramed`].
39     ///
40     /// [`UdpFramed`]: https://docs.rs/tokio-util/latest/tokio_util/udp/struct.UdpFramed.html
41     /// [`Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html
42     ///
43     /// # Example: one to many (bind)
44     ///
45     /// Using `bind` we can create a simple echo server that sends and recv's with many different clients:
46     /// ```no_run
47     /// use tokio::net::UdpSocket;
48     /// use std::io;
49     ///
50     /// #[tokio::main]
51     /// async fn main() -> io::Result<()> {
52     ///     let sock = UdpSocket::bind("0.0.0.0:8080").await?;
53     ///     let mut buf = [0; 1024];
54     ///     loop {
55     ///         let (len, addr) = sock.recv_from(&mut buf).await?;
56     ///         println!("{:?} bytes received from {:?}", len, addr);
57     ///
58     ///         let len = sock.send_to(&buf[..len], addr).await?;
59     ///         println!("{:?} bytes sent", len);
60     ///     }
61     /// }
62     /// ```
63     ///
64     /// # Example: one to one (connect)
65     ///
66     /// Or using `connect` we can echo with a single remote address using `send` and `recv`:
67     /// ```no_run
68     /// use tokio::net::UdpSocket;
69     /// use std::io;
70     ///
71     /// #[tokio::main]
72     /// async fn main() -> io::Result<()> {
73     ///     let sock = UdpSocket::bind("0.0.0.0:8080").await?;
74     ///
75     ///     let remote_addr = "127.0.0.1:59611";
76     ///     sock.connect(remote_addr).await?;
77     ///     let mut buf = [0; 1024];
78     ///     loop {
79     ///         let len = sock.recv(&mut buf).await?;
80     ///         println!("{:?} bytes received from {:?}", len, remote_addr);
81     ///
82     ///         let len = sock.send(&buf[..len]).await?;
83     ///         println!("{:?} bytes sent", len);
84     ///     }
85     /// }
86     /// ```
87     ///
88     /// # Example: Splitting with `Arc`
89     ///
90     /// Because `send_to` and `recv_from` take `&self`. It's perfectly alright
91     /// to use an `Arc<UdpSocket>` and share the references to multiple tasks.
92     /// Here is a similar "echo" example that supports concurrent
93     /// sending/receiving:
94     ///
95     /// ```no_run
96     /// use tokio::{net::UdpSocket, sync::mpsc};
97     /// use std::{io, net::SocketAddr, sync::Arc};
98     ///
99     /// #[tokio::main]
100     /// async fn main() -> io::Result<()> {
101     ///     let sock = UdpSocket::bind("0.0.0.0:8080".parse::<SocketAddr>().unwrap()).await?;
102     ///     let r = Arc::new(sock);
103     ///     let s = r.clone();
104     ///     let (tx, mut rx) = mpsc::channel::<(Vec<u8>, SocketAddr)>(1_000);
105     ///
106     ///     tokio::spawn(async move {
107     ///         while let Some((bytes, addr)) = rx.recv().await {
108     ///             let len = s.send_to(&bytes, &addr).await.unwrap();
109     ///             println!("{:?} bytes sent", len);
110     ///         }
111     ///     });
112     ///
113     ///     let mut buf = [0; 1024];
114     ///     loop {
115     ///         let (len, addr) = r.recv_from(&mut buf).await?;
116     ///         println!("{:?} bytes received from {:?}", len, addr);
117     ///         tx.send((buf[..len].to_vec(), addr)).await.unwrap();
118     ///     }
119     /// }
120     /// ```
121     ///
122     pub struct UdpSocket {
123         io: PollEvented<mio::net::UdpSocket>,
124     }
125 }
126 
127 impl UdpSocket {
128     /// This function will create a new UDP socket and attempt to bind it to
129     /// the `addr` provided.
130     ///
131     /// # Example
132     ///
133     /// ```no_run
134     /// use tokio::net::UdpSocket;
135     /// use std::io;
136     ///
137     /// #[tokio::main]
138     /// async fn main() -> io::Result<()> {
139     ///     let sock = UdpSocket::bind("0.0.0.0:8080").await?;
140     ///     // use `sock`
141     /// #   let _ = sock;
142     ///     Ok(())
143     /// }
144     /// ```
bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket>145     pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
146         let addrs = to_socket_addrs(addr).await?;
147         let mut last_err = None;
148 
149         for addr in addrs {
150             match UdpSocket::bind_addr(addr) {
151                 Ok(socket) => return Ok(socket),
152                 Err(e) => last_err = Some(e),
153             }
154         }
155 
156         Err(last_err.unwrap_or_else(|| {
157             io::Error::new(
158                 io::ErrorKind::InvalidInput,
159                 "could not resolve to any address",
160             )
161         }))
162     }
163 
bind_addr(addr: SocketAddr) -> io::Result<UdpSocket>164     fn bind_addr(addr: SocketAddr) -> io::Result<UdpSocket> {
165         let sys = mio::net::UdpSocket::bind(addr)?;
166         UdpSocket::new(sys)
167     }
168 
new(socket: mio::net::UdpSocket) -> io::Result<UdpSocket>169     fn new(socket: mio::net::UdpSocket) -> io::Result<UdpSocket> {
170         let io = PollEvented::new(socket)?;
171         Ok(UdpSocket { io })
172     }
173 
174     /// Creates new `UdpSocket` from a previously bound `std::net::UdpSocket`.
175     ///
176     /// This function is intended to be used to wrap a UDP socket from the
177     /// standard library in the Tokio equivalent. The conversion assumes nothing
178     /// about the underlying socket; it is left up to the user to set it in
179     /// non-blocking mode.
180     ///
181     /// This can be used in conjunction with socket2's `Socket` interface to
182     /// configure a socket before it's handed off, such as setting options like
183     /// `reuse_address` or binding to multiple addresses.
184     ///
185     /// # Panics
186     ///
187     /// This function panics if thread-local runtime is not set.
188     ///
189     /// The runtime is usually set implicitly when this function is called
190     /// from a future driven by a tokio runtime, otherwise runtime can be set
191     /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
192     ///
193     /// # Example
194     ///
195     /// ```no_run
196     /// use tokio::net::UdpSocket;
197     /// # use std::{io, net::SocketAddr};
198     ///
199     /// # #[tokio::main]
200     /// # async fn main() -> io::Result<()> {
201     /// let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
202     /// let std_sock = std::net::UdpSocket::bind(addr)?;
203     /// std_sock.set_nonblocking(true)?;
204     /// let sock = UdpSocket::from_std(std_sock)?;
205     /// // use `sock`
206     /// # Ok(())
207     /// # }
208     /// ```
from_std(socket: net::UdpSocket) -> io::Result<UdpSocket>209     pub fn from_std(socket: net::UdpSocket) -> io::Result<UdpSocket> {
210         let io = mio::net::UdpSocket::from_std(socket);
211         UdpSocket::new(io)
212     }
213 
214     /// Turn a [`tokio::net::UdpSocket`] into a [`std::net::UdpSocket`].
215     ///
216     /// The returned [`std::net::UdpSocket`] will have nonblocking mode set as
217     /// `true`.  Use [`set_nonblocking`] to change the blocking mode if needed.
218     ///
219     /// # Examples
220     ///
221     /// ```rust,no_run
222     /// use std::error::Error;
223     ///
224     /// #[tokio::main]
225     /// async fn main() -> Result<(), Box<dyn Error>> {
226     ///     let tokio_socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await?;
227     ///     let std_socket = tokio_socket.into_std()?;
228     ///     std_socket.set_nonblocking(false)?;
229     ///     Ok(())
230     /// }
231     /// ```
232     ///
233     /// [`tokio::net::UdpSocket`]: UdpSocket
234     /// [`std::net::UdpSocket`]: std::net::UdpSocket
235     /// [`set_nonblocking`]: fn@std::net::UdpSocket::set_nonblocking
into_std(self) -> io::Result<std::net::UdpSocket>236     pub fn into_std(self) -> io::Result<std::net::UdpSocket> {
237         #[cfg(unix)]
238         {
239             use std::os::unix::io::{FromRawFd, IntoRawFd};
240             self.io
241                 .into_inner()
242                 .map(|io| io.into_raw_fd())
243                 .map(|raw_fd| unsafe { std::net::UdpSocket::from_raw_fd(raw_fd) })
244         }
245 
246         #[cfg(windows)]
247         {
248             use std::os::windows::io::{FromRawSocket, IntoRawSocket};
249             self.io
250                 .into_inner()
251                 .map(|io| io.into_raw_socket())
252                 .map(|raw_socket| unsafe { std::net::UdpSocket::from_raw_socket(raw_socket) })
253         }
254     }
255 
256     /// Returns the local address that this socket is bound to.
257     ///
258     /// # Example
259     ///
260     /// ```no_run
261     /// use tokio::net::UdpSocket;
262     /// # use std::{io, net::SocketAddr};
263     ///
264     /// # #[tokio::main]
265     /// # async fn main() -> io::Result<()> {
266     /// let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
267     /// let sock = UdpSocket::bind(addr).await?;
268     /// // the address the socket is bound to
269     /// let local_addr = sock.local_addr()?;
270     /// # Ok(())
271     /// # }
272     /// ```
local_addr(&self) -> io::Result<SocketAddr>273     pub fn local_addr(&self) -> io::Result<SocketAddr> {
274         self.io.local_addr()
275     }
276 
277     /// Connects the UDP socket setting the default destination for send() and
278     /// limiting packets that are read via recv from the address specified in
279     /// `addr`.
280     ///
281     /// # Example
282     ///
283     /// ```no_run
284     /// use tokio::net::UdpSocket;
285     /// # use std::{io, net::SocketAddr};
286     ///
287     /// # #[tokio::main]
288     /// # async fn main() -> io::Result<()> {
289     /// let sock = UdpSocket::bind("0.0.0.0:8080".parse::<SocketAddr>().unwrap()).await?;
290     ///
291     /// let remote_addr = "127.0.0.1:59600".parse::<SocketAddr>().unwrap();
292     /// sock.connect(remote_addr).await?;
293     /// let mut buf = [0u8; 32];
294     /// // recv from remote_addr
295     /// let len = sock.recv(&mut buf).await?;
296     /// // send to remote_addr
297     /// let _len = sock.send(&buf[..len]).await?;
298     /// # Ok(())
299     /// # }
300     /// ```
connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()>301     pub async fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
302         let addrs = to_socket_addrs(addr).await?;
303         let mut last_err = None;
304 
305         for addr in addrs {
306             match self.io.connect(addr) {
307                 Ok(_) => return Ok(()),
308                 Err(e) => last_err = Some(e),
309             }
310         }
311 
312         Err(last_err.unwrap_or_else(|| {
313             io::Error::new(
314                 io::ErrorKind::InvalidInput,
315                 "could not resolve to any address",
316             )
317         }))
318     }
319 
320     /// Wait for any of the requested ready states.
321     ///
322     /// This function is usually paired with `try_recv()` or `try_send()`. It
323     /// can be used to concurrently recv / send to the same socket on a single
324     /// task without splitting the socket.
325     ///
326     /// The function may complete without the socket being ready. This is a
327     /// false-positive and attempting an operation will return with
328     /// `io::ErrorKind::WouldBlock`.
329     ///
330     /// # Examples
331     ///
332     /// Concurrently receive from and send to the socket on the same task
333     /// without splitting.
334     ///
335     /// ```no_run
336     /// use tokio::io::{self, Interest};
337     /// use tokio::net::UdpSocket;
338     ///
339     /// #[tokio::main]
340     /// async fn main() -> io::Result<()> {
341     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
342     ///     socket.connect("127.0.0.1:8081").await?;
343     ///
344     ///     loop {
345     ///         let ready = socket.ready(Interest::READABLE | Interest::WRITABLE).await?;
346     ///
347     ///         if ready.is_readable() {
348     ///             // The buffer is **not** included in the async task and will only exist
349     ///             // on the stack.
350     ///             let mut data = [0; 1024];
351     ///             match socket.try_recv(&mut data[..]) {
352     ///                 Ok(n) => {
353     ///                     println!("received {:?}", &data[..n]);
354     ///                 }
355     ///                 // False-positive, continue
356     ///                 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
357     ///                 Err(e) => {
358     ///                     return Err(e);
359     ///                 }
360     ///             }
361     ///         }
362     ///
363     ///         if ready.is_writable() {
364     ///             // Write some data
365     ///             match socket.try_send(b"hello world") {
366     ///                 Ok(n) => {
367     ///                     println!("sent {} bytes", n);
368     ///                 }
369     ///                 // False-positive, continue
370     ///                 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
371     ///                 Err(e) => {
372     ///                     return Err(e);
373     ///                 }
374     ///             }
375     ///         }
376     ///     }
377     /// }
378     /// ```
ready(&self, interest: Interest) -> io::Result<Ready>379     pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
380         let event = self.io.registration().readiness(interest).await?;
381         Ok(event.ready)
382     }
383 
384     /// Wait for the socket to become writable.
385     ///
386     /// This function is equivalent to `ready(Interest::WRITABLE)` and is
387     /// usually paired with `try_send()` or `try_send_to()`.
388     ///
389     /// The function may complete without the socket being writable. This is a
390     /// false-positive and attempting a `try_send()` will return with
391     /// `io::ErrorKind::WouldBlock`.
392     ///
393     /// # Examples
394     ///
395     /// ```no_run
396     /// use tokio::net::UdpSocket;
397     /// use std::io;
398     ///
399     /// #[tokio::main]
400     /// async fn main() -> io::Result<()> {
401     ///     // Bind socket
402     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
403     ///     socket.connect("127.0.0.1:8081").await?;
404     ///
405     ///     loop {
406     ///         // Wait for the socket to be writable
407     ///         socket.writable().await?;
408     ///
409     ///         // Try to send data, this may still fail with `WouldBlock`
410     ///         // if the readiness event is a false positive.
411     ///         match socket.try_send(b"hello world") {
412     ///             Ok(n) => {
413     ///                 break;
414     ///             }
415     ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
416     ///                 continue;
417     ///             }
418     ///             Err(e) => {
419     ///                 return Err(e);
420     ///             }
421     ///         }
422     ///     }
423     ///
424     ///     Ok(())
425     /// }
426     /// ```
writable(&self) -> io::Result<()>427     pub async fn writable(&self) -> io::Result<()> {
428         self.ready(Interest::WRITABLE).await?;
429         Ok(())
430     }
431 
432     /// Sends data on the socket to the remote address that the socket is
433     /// connected to.
434     ///
435     /// The [`connect`] method will connect this socket to a remote address.
436     /// This method will fail if the socket is not connected.
437     ///
438     /// [`connect`]: method@Self::connect
439     ///
440     /// # Return
441     ///
442     /// On success, the number of bytes sent is returned, otherwise, the
443     /// encountered error is returned.
444     ///
445     /// # Examples
446     ///
447     /// ```no_run
448     /// use tokio::io;
449     /// use tokio::net::UdpSocket;
450     ///
451     /// #[tokio::main]
452     /// async fn main() -> io::Result<()> {
453     ///     // Bind socket
454     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
455     ///     socket.connect("127.0.0.1:8081").await?;
456     ///
457     ///     // Send a message
458     ///     socket.send(b"hello world").await?;
459     ///
460     ///     Ok(())
461     /// }
462     /// ```
send(&self, buf: &[u8]) -> io::Result<usize>463     pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
464         self.io
465             .registration()
466             .async_io(Interest::WRITABLE, || self.io.send(buf))
467             .await
468     }
469 
470     /// Attempts to send data on the socket to the remote address to which it
471     /// was previously `connect`ed.
472     ///
473     /// The [`connect`] method will connect this socket to a remote address.
474     /// This method will fail if the socket is not connected.
475     ///
476     /// Note that on multiple calls to a `poll_*` method in the send direction,
477     /// only the `Waker` from the `Context` passed to the most recent call will
478     /// be scheduled to receive a wakeup.
479     ///
480     /// # Return value
481     ///
482     /// The function returns:
483     ///
484     /// * `Poll::Pending` if the socket is not available to write
485     /// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent
486     /// * `Poll::Ready(Err(e))` if an error is encountered.
487     ///
488     /// # Errors
489     ///
490     /// This function may encounter any standard I/O error except `WouldBlock`.
491     ///
492     /// [`connect`]: method@Self::connect
poll_send(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>>493     pub fn poll_send(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
494         self.io
495             .registration()
496             .poll_write_io(cx, || self.io.send(buf))
497     }
498 
499     /// Try to send data on the socket to the remote address to which it is
500     /// connected.
501     ///
502     /// When the socket buffer is full, `Err(io::ErrorKind::WouldBlock)` is
503     /// returned. This function is usually paired with `writable()`.
504     ///
505     /// # Returns
506     ///
507     /// If successful, `Ok(n)` is returned, where `n` is the number of bytes
508     /// sent. If the socket is not ready to send data,
509     /// `Err(ErrorKind::WouldBlock)` is returned.
510     ///
511     /// # Examples
512     ///
513     /// ```no_run
514     /// use tokio::net::UdpSocket;
515     /// use std::io;
516     ///
517     /// #[tokio::main]
518     /// async fn main() -> io::Result<()> {
519     ///     // Bind a UDP socket
520     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
521     ///
522     ///     // Connect to a peer
523     ///     socket.connect("127.0.0.1:8081").await?;
524     ///
525     ///     loop {
526     ///         // Wait for the socket to be writable
527     ///         socket.writable().await?;
528     ///
529     ///         // Try to send data, this may still fail with `WouldBlock`
530     ///         // if the readiness event is a false positive.
531     ///         match socket.try_send(b"hello world") {
532     ///             Ok(n) => {
533     ///                 break;
534     ///             }
535     ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
536     ///                 continue;
537     ///             }
538     ///             Err(e) => {
539     ///                 return Err(e);
540     ///             }
541     ///         }
542     ///     }
543     ///
544     ///     Ok(())
545     /// }
546     /// ```
try_send(&self, buf: &[u8]) -> io::Result<usize>547     pub fn try_send(&self, buf: &[u8]) -> io::Result<usize> {
548         self.io
549             .registration()
550             .try_io(Interest::WRITABLE, || self.io.send(buf))
551     }
552 
553     /// Wait for the socket to become readable.
554     ///
555     /// This function is equivalent to `ready(Interest::READABLE)` and is usually
556     /// paired with `try_recv()`.
557     ///
558     /// The function may complete without the socket being readable. This is a
559     /// false-positive and attempting a `try_recv()` will return with
560     /// `io::ErrorKind::WouldBlock`.
561     ///
562     /// # Examples
563     ///
564     /// ```no_run
565     /// use tokio::net::UdpSocket;
566     /// use std::io;
567     ///
568     /// #[tokio::main]
569     /// async fn main() -> io::Result<()> {
570     ///     // Connect to a peer
571     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
572     ///     socket.connect("127.0.0.1:8081").await?;
573     ///
574     ///     loop {
575     ///         // Wait for the socket to be readable
576     ///         socket.readable().await?;
577     ///
578     ///         // The buffer is **not** included in the async task and will
579     ///         // only exist on the stack.
580     ///         let mut buf = [0; 1024];
581     ///
582     ///         // Try to recv data, this may still fail with `WouldBlock`
583     ///         // if the readiness event is a false positive.
584     ///         match socket.try_recv(&mut buf) {
585     ///             Ok(n) => {
586     ///                 println!("GOT {:?}", &buf[..n]);
587     ///                 break;
588     ///             }
589     ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
590     ///                 continue;
591     ///             }
592     ///             Err(e) => {
593     ///                 return Err(e);
594     ///             }
595     ///         }
596     ///     }
597     ///
598     ///     Ok(())
599     /// }
600     /// ```
readable(&self) -> io::Result<()>601     pub async fn readable(&self) -> io::Result<()> {
602         self.ready(Interest::READABLE).await?;
603         Ok(())
604     }
605 
606     /// Receives a single datagram message on the socket from the remote address
607     /// to which it is connected. On success, returns the number of bytes read.
608     ///
609     /// The function must be called with valid byte array `buf` of sufficient
610     /// size to hold the message bytes. If a message is too long to fit in the
611     /// supplied buffer, excess bytes may be discarded.
612     ///
613     /// The [`connect`] method will connect this socket to a remote address.
614     /// This method will fail if the socket is not connected.
615     ///
616     /// [`connect`]: method@Self::connect
617     ///
618     /// ```no_run
619     /// use tokio::net::UdpSocket;
620     /// use std::io;
621     ///
622     /// #[tokio::main]
623     /// async fn main() -> io::Result<()> {
624     ///     // Bind socket
625     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
626     ///     socket.connect("127.0.0.1:8081").await?;
627     ///
628     ///     let mut buf = vec![0; 10];
629     ///     let n = socket.recv(&mut buf).await?;
630     ///
631     ///     println!("received {} bytes {:?}", n, &buf[..n]);
632     ///
633     ///     Ok(())
634     /// }
635     /// ```
recv(&self, buf: &mut [u8]) -> io::Result<usize>636     pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
637         self.io
638             .registration()
639             .async_io(Interest::READABLE, || self.io.recv(buf))
640             .await
641     }
642 
643     /// Attempts to receive a single datagram message on the socket from the remote
644     /// address to which it is `connect`ed.
645     ///
646     /// The [`connect`] method will connect this socket to a remote address. This method
647     /// resolves to an error if the socket is not connected.
648     ///
649     /// Note that on multiple calls to a `poll_*` method in the recv direction, only the
650     /// `Waker` from the `Context` passed to the most recent call will be scheduled to
651     /// receive a wakeup.
652     ///
653     /// # Return value
654     ///
655     /// The function returns:
656     ///
657     /// * `Poll::Pending` if the socket is not ready to read
658     /// * `Poll::Ready(Ok(()))` reads data `ReadBuf` if the socket is ready
659     /// * `Poll::Ready(Err(e))` if an error is encountered.
660     ///
661     /// # Errors
662     ///
663     /// This function may encounter any standard I/O error except `WouldBlock`.
664     ///
665     /// [`connect`]: method@Self::connect
poll_recv(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>>666     pub fn poll_recv(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
667         let n = ready!(self.io.registration().poll_read_io(cx, || {
668             // Safety: will not read the maybe uinitialized bytes.
669             let b = unsafe {
670                 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
671             };
672 
673             self.io.recv(b)
674         }))?;
675 
676         // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
677         unsafe {
678             buf.assume_init(n);
679         }
680         buf.advance(n);
681         Poll::Ready(Ok(()))
682     }
683 
684     /// Try to receive a single datagram message on the socket from the remote
685     /// address to which it is connected. On success, returns the number of
686     /// bytes read.
687     ///
688     /// The function must be called with valid byte array buf of sufficient size
689     /// to hold the message bytes. If a message is too long to fit in the
690     /// supplied buffer, excess bytes may be discarded.
691     ///
692     /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
693     /// returned. This function is usually paired with `readable()`.
694     ///
695     /// # Examples
696     ///
697     /// ```no_run
698     /// use tokio::net::UdpSocket;
699     /// use std::io;
700     ///
701     /// #[tokio::main]
702     /// async fn main() -> io::Result<()> {
703     ///     // Connect to a peer
704     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
705     ///     socket.connect("127.0.0.1:8081").await?;
706     ///
707     ///     loop {
708     ///         // Wait for the socket to be readable
709     ///         socket.readable().await?;
710     ///
711     ///         // The buffer is **not** included in the async task and will
712     ///         // only exist on the stack.
713     ///         let mut buf = [0; 1024];
714     ///
715     ///         // Try to recv data, this may still fail with `WouldBlock`
716     ///         // if the readiness event is a false positive.
717     ///         match socket.try_recv(&mut buf) {
718     ///             Ok(n) => {
719     ///                 println!("GOT {:?}", &buf[..n]);
720     ///                 break;
721     ///             }
722     ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
723     ///                 continue;
724     ///             }
725     ///             Err(e) => {
726     ///                 return Err(e);
727     ///             }
728     ///         }
729     ///     }
730     ///
731     ///     Ok(())
732     /// }
733     /// ```
try_recv(&self, buf: &mut [u8]) -> io::Result<usize>734     pub fn try_recv(&self, buf: &mut [u8]) -> io::Result<usize> {
735         self.io
736             .registration()
737             .try_io(Interest::READABLE, || self.io.recv(buf))
738     }
739 
740     cfg_io_util! {
741         /// Try to receive data from the stream into the provided buffer, advancing the
742         /// buffer's internal cursor, returning how many bytes were read.
743         ///
744         /// The function must be called with valid byte array buf of sufficient size
745         /// to hold the message bytes. If a message is too long to fit in the
746         /// supplied buffer, excess bytes may be discarded.
747         ///
748         /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
749         /// returned. This function is usually paired with `readable()`.
750         ///
751         /// # Examples
752         ///
753         /// ```no_run
754         /// use tokio::net::UdpSocket;
755         /// use std::io;
756         ///
757         /// #[tokio::main]
758         /// async fn main() -> io::Result<()> {
759         ///     // Connect to a peer
760         ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
761         ///     socket.connect("127.0.0.1:8081").await?;
762         ///
763         ///     loop {
764         ///         // Wait for the socket to be readable
765         ///         socket.readable().await?;
766         ///
767         ///         let mut buf = Vec::with_capacity(1024);
768         ///
769         ///         // Try to recv data, this may still fail with `WouldBlock`
770         ///         // if the readiness event is a false positive.
771         ///         match socket.try_recv_buf(&mut buf) {
772         ///             Ok(n) => {
773         ///                 println!("GOT {:?}", &buf[..n]);
774         ///                 break;
775         ///             }
776         ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
777         ///                 continue;
778         ///             }
779         ///             Err(e) => {
780         ///                 return Err(e);
781         ///             }
782         ///         }
783         ///     }
784         ///
785         ///     Ok(())
786         /// }
787         /// ```
788         pub fn try_recv_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
789             self.io.registration().try_io(Interest::READABLE, || {
790                 let dst = buf.chunk_mut();
791                 let dst =
792                     unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
793 
794                 // Safety: We trust `UdpSocket::recv` to have filled up `n` bytes in the
795                 // buffer.
796                 let n = (&*self.io).recv(dst)?;
797 
798                 unsafe {
799                     buf.advance_mut(n);
800                 }
801 
802                 Ok(n)
803             })
804         }
805 
806         /// Try to receive a single datagram message on the socket. On success,
807         /// returns the number of bytes read and the origin.
808         ///
809         /// The function must be called with valid byte array buf of sufficient size
810         /// to hold the message bytes. If a message is too long to fit in the
811         /// supplied buffer, excess bytes may be discarded.
812         ///
813         /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
814         /// returned. This function is usually paired with `readable()`.
815         ///
816         /// # Examples
817         ///
818         /// ```no_run
819         /// use tokio::net::UdpSocket;
820         /// use std::io;
821         ///
822         /// #[tokio::main]
823         /// async fn main() -> io::Result<()> {
824         ///     // Connect to a peer
825         ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
826         ///
827         ///     loop {
828         ///         // Wait for the socket to be readable
829         ///         socket.readable().await?;
830         ///
831         ///         let mut buf = Vec::with_capacity(1024);
832         ///
833         ///         // Try to recv data, this may still fail with `WouldBlock`
834         ///         // if the readiness event is a false positive.
835         ///         match socket.try_recv_buf_from(&mut buf) {
836         ///             Ok((n, _addr)) => {
837         ///                 println!("GOT {:?}", &buf[..n]);
838         ///                 break;
839         ///             }
840         ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
841         ///                 continue;
842         ///             }
843         ///             Err(e) => {
844         ///                 return Err(e);
845         ///             }
846         ///         }
847         ///     }
848         ///
849         ///     Ok(())
850         /// }
851         /// ```
852         pub fn try_recv_buf_from<B: BufMut>(&self, buf: &mut B) -> io::Result<(usize, SocketAddr)> {
853             self.io.registration().try_io(Interest::READABLE, || {
854                 let dst = buf.chunk_mut();
855                 let dst =
856                     unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
857 
858                 // Safety: We trust `UdpSocket::recv_from` to have filled up `n` bytes in the
859                 // buffer.
860                 let (n, addr) = (&*self.io).recv_from(dst)?;
861 
862                 unsafe {
863                     buf.advance_mut(n);
864                 }
865 
866                 Ok((n, addr))
867             })
868         }
869     }
870 
871     /// Sends data on the socket to the given address. On success, returns the
872     /// number of bytes written.
873     ///
874     /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
875     /// documentation for concrete examples.
876     ///
877     /// It is possible for `addr` to yield multiple addresses, but `send_to`
878     /// will only send data to the first address yielded by `addr`.
879     ///
880     /// This will return an error when the IP version of the local socket does
881     /// not match that returned from [`ToSocketAddrs`].
882     ///
883     /// [`ToSocketAddrs`]: crate::net::ToSocketAddrs
884     ///
885     /// # Example
886     ///
887     /// ```no_run
888     /// use tokio::net::UdpSocket;
889     /// use std::io;
890     ///
891     /// #[tokio::main]
892     /// async fn main() -> io::Result<()> {
893     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
894     ///     let len = socket.send_to(b"hello world", "127.0.0.1:8081").await?;
895     ///
896     ///     println!("Sent {} bytes", len);
897     ///
898     ///     Ok(())
899     /// }
900     /// ```
send_to<A: ToSocketAddrs>(&self, buf: &[u8], target: A) -> io::Result<usize>901     pub async fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], target: A) -> io::Result<usize> {
902         let mut addrs = to_socket_addrs(target).await?;
903 
904         match addrs.next() {
905             Some(target) => self.send_to_addr(buf, target).await,
906             None => Err(io::Error::new(
907                 io::ErrorKind::InvalidInput,
908                 "no addresses to send data to",
909             )),
910         }
911     }
912 
913     /// Attempts to send data on the socket to a given address.
914     ///
915     /// Note that on multiple calls to a `poll_*` method in the send direction, only the
916     /// `Waker` from the `Context` passed to the most recent call will be scheduled to
917     /// receive a wakeup.
918     ///
919     /// # Return value
920     ///
921     /// The function returns:
922     ///
923     /// * `Poll::Pending` if the socket is not ready to write
924     /// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent.
925     /// * `Poll::Ready(Err(e))` if an error is encountered.
926     ///
927     /// # Errors
928     ///
929     /// This function may encounter any standard I/O error except `WouldBlock`.
poll_send_to( &self, cx: &mut Context<'_>, buf: &[u8], target: SocketAddr, ) -> Poll<io::Result<usize>>930     pub fn poll_send_to(
931         &self,
932         cx: &mut Context<'_>,
933         buf: &[u8],
934         target: SocketAddr,
935     ) -> Poll<io::Result<usize>> {
936         self.io
937             .registration()
938             .poll_write_io(cx, || self.io.send_to(buf, target))
939     }
940 
941     /// Try to send data on the socket to the given address, but if the send is
942     /// blocked this will return right away.
943     ///
944     /// This function is usually paired with `writable()`.
945     ///
946     /// # Returns
947     ///
948     /// If successfull, returns the number of bytes sent
949     ///
950     /// Users should ensure that when the remote cannot receive, the
951     /// [`ErrorKind::WouldBlock`] is properly handled. An error can also occur
952     /// if the IP version of the socket does not match that of `target`.
953     ///
954     /// [`ErrorKind::WouldBlock`]: std::io::ErrorKind::WouldBlock
955     ///
956     /// # Example
957     ///
958     /// ```no_run
959     /// use tokio::net::UdpSocket;
960     /// use std::error::Error;
961     /// use std::io;
962     ///
963     /// #[tokio::main]
964     /// async fn main() -> Result<(), Box<dyn Error>> {
965     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
966     ///
967     ///     let dst = "127.0.0.1:8081".parse()?;
968     ///
969     ///     loop {
970     ///         socket.writable().await?;
971     ///
972     ///         match socket.try_send_to(&b"hello world"[..], dst) {
973     ///             Ok(sent) => {
974     ///                 println!("sent {} bytes", sent);
975     ///                 break;
976     ///             }
977     ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
978     ///                 // Writable false positive.
979     ///                 continue;
980     ///             }
981     ///             Err(e) => return Err(e.into()),
982     ///         }
983     ///     }
984     ///
985     ///     Ok(())
986     /// }
987     /// ```
try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize>988     pub fn try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
989         self.io
990             .registration()
991             .try_io(Interest::WRITABLE, || self.io.send_to(buf, target))
992     }
993 
send_to_addr(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize>994     async fn send_to_addr(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
995         self.io
996             .registration()
997             .async_io(Interest::WRITABLE, || self.io.send_to(buf, target))
998             .await
999     }
1000 
1001     /// Receives a single datagram message on the socket. On success, returns
1002     /// the number of bytes read and the origin.
1003     ///
1004     /// The function must be called with valid byte array `buf` of sufficient
1005     /// size to hold the message bytes. If a message is too long to fit in the
1006     /// supplied buffer, excess bytes may be discarded.
1007     ///
1008     /// # Example
1009     ///
1010     /// ```no_run
1011     /// use tokio::net::UdpSocket;
1012     /// use std::io;
1013     ///
1014     /// #[tokio::main]
1015     /// async fn main() -> io::Result<()> {
1016     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1017     ///
1018     ///     let mut buf = vec![0u8; 32];
1019     ///     let (len, addr) = socket.recv_from(&mut buf).await?;
1020     ///
1021     ///     println!("received {:?} bytes from {:?}", len, addr);
1022     ///
1023     ///     Ok(())
1024     /// }
1025     /// ```
recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)>1026     pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1027         self.io
1028             .registration()
1029             .async_io(Interest::READABLE, || self.io.recv_from(buf))
1030             .await
1031     }
1032 
1033     /// Attempts to receive a single datagram on the socket.
1034     ///
1035     /// Note that on multiple calls to a `poll_*` method in the recv direction, only the
1036     /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1037     /// receive a wakeup.
1038     ///
1039     /// # Return value
1040     ///
1041     /// The function returns:
1042     ///
1043     /// * `Poll::Pending` if the socket is not ready to read
1044     /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1045     /// * `Poll::Ready(Err(e))` if an error is encountered.
1046     ///
1047     /// # Errors
1048     ///
1049     /// This function may encounter any standard I/O error except `WouldBlock`.
poll_recv_from( &self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<SocketAddr>>1050     pub fn poll_recv_from(
1051         &self,
1052         cx: &mut Context<'_>,
1053         buf: &mut ReadBuf<'_>,
1054     ) -> Poll<io::Result<SocketAddr>> {
1055         let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1056             // Safety: will not read the maybe uinitialized bytes.
1057             let b = unsafe {
1058                 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1059             };
1060 
1061             self.io.recv_from(b)
1062         }))?;
1063 
1064         // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1065         unsafe {
1066             buf.assume_init(n);
1067         }
1068         buf.advance(n);
1069         Poll::Ready(Ok(addr))
1070     }
1071 
1072     /// Try to receive a single datagram message on the socket. On success,
1073     /// returns the number of bytes read and the origin.
1074     ///
1075     /// The function must be called with valid byte array buf of sufficient size
1076     /// to hold the message bytes. If a message is too long to fit in the
1077     /// supplied buffer, excess bytes may be discarded.
1078     ///
1079     /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1080     /// returned. This function is usually paired with `readable()`.
1081     ///
1082     /// # Examples
1083     ///
1084     /// ```no_run
1085     /// use tokio::net::UdpSocket;
1086     /// use std::io;
1087     ///
1088     /// #[tokio::main]
1089     /// async fn main() -> io::Result<()> {
1090     ///     // Connect to a peer
1091     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1092     ///
1093     ///     loop {
1094     ///         // Wait for the socket to be readable
1095     ///         socket.readable().await?;
1096     ///
1097     ///         // The buffer is **not** included in the async task and will
1098     ///         // only exist on the stack.
1099     ///         let mut buf = [0; 1024];
1100     ///
1101     ///         // Try to recv data, this may still fail with `WouldBlock`
1102     ///         // if the readiness event is a false positive.
1103     ///         match socket.try_recv_from(&mut buf) {
1104     ///             Ok((n, _addr)) => {
1105     ///                 println!("GOT {:?}", &buf[..n]);
1106     ///                 break;
1107     ///             }
1108     ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1109     ///                 continue;
1110     ///             }
1111     ///             Err(e) => {
1112     ///                 return Err(e);
1113     ///             }
1114     ///         }
1115     ///     }
1116     ///
1117     ///     Ok(())
1118     /// }
1119     /// ```
try_recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)>1120     pub fn try_recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1121         self.io
1122             .registration()
1123             .try_io(Interest::READABLE, || self.io.recv_from(buf))
1124     }
1125 
1126     /// Receives data from the socket, without removing it from the input queue.
1127     /// On success, returns the number of bytes read and the address from whence
1128     /// the data came.
1129     ///
1130     /// # Notes
1131     ///
1132     /// On Windows, if the data is larger than the buffer specified, the buffer
1133     /// is filled with the first part of the data, and peek_from returns the error
1134     /// WSAEMSGSIZE(10040). The excess data is lost.
1135     /// Make sure to always use a sufficiently large buffer to hold the
1136     /// maximum UDP packet size, which can be up to 65536 bytes in size.
1137     ///
1138     /// # Examples
1139     ///
1140     /// ```no_run
1141     /// use tokio::net::UdpSocket;
1142     /// use std::io;
1143     ///
1144     /// #[tokio::main]
1145     /// async fn main() -> io::Result<()> {
1146     ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1147     ///
1148     ///     let mut buf = vec![0u8; 32];
1149     ///     let (len, addr) = socket.peek_from(&mut buf).await?;
1150     ///
1151     ///     println!("peeked {:?} bytes from {:?}", len, addr);
1152     ///
1153     ///     Ok(())
1154     /// }
1155     /// ```
peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)>1156     pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1157         self.io
1158             .registration()
1159             .async_io(Interest::READABLE, || self.io.peek_from(buf))
1160             .await
1161     }
1162 
1163     /// Receives data from the socket, without removing it from the input queue.
1164     /// On success, returns the number of bytes read.
1165     ///
1166     /// # Notes
1167     ///
1168     /// Note that on multiple calls to a `poll_*` method in the recv direction, only the
1169     /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1170     /// receive a wakeup
1171     ///
1172     /// On Windows, if the data is larger than the buffer specified, the buffer
1173     /// is filled with the first part of the data, and peek returns the error
1174     /// WSAEMSGSIZE(10040). The excess data is lost.
1175     /// Make sure to always use a sufficiently large buffer to hold the
1176     /// maximum UDP packet size, which can be up to 65536 bytes in size.
1177     ///
1178     /// # Return value
1179     ///
1180     /// The function returns:
1181     ///
1182     /// * `Poll::Pending` if the socket is not ready to read
1183     /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1184     /// * `Poll::Ready(Err(e))` if an error is encountered.
1185     ///
1186     /// # Errors
1187     ///
1188     /// This function may encounter any standard I/O error except `WouldBlock`.
poll_peek_from( &self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<SocketAddr>>1189     pub fn poll_peek_from(
1190         &self,
1191         cx: &mut Context<'_>,
1192         buf: &mut ReadBuf<'_>,
1193     ) -> Poll<io::Result<SocketAddr>> {
1194         let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1195             // Safety: will not read the maybe uinitialized bytes.
1196             let b = unsafe {
1197                 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1198             };
1199 
1200             self.io.peek_from(b)
1201         }))?;
1202 
1203         // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1204         unsafe {
1205             buf.assume_init(n);
1206         }
1207         buf.advance(n);
1208         Poll::Ready(Ok(addr))
1209     }
1210 
1211     /// Gets the value of the `SO_BROADCAST` option for this socket.
1212     ///
1213     /// For more information about this option, see [`set_broadcast`].
1214     ///
1215     /// [`set_broadcast`]: method@Self::set_broadcast
broadcast(&self) -> io::Result<bool>1216     pub fn broadcast(&self) -> io::Result<bool> {
1217         self.io.broadcast()
1218     }
1219 
1220     /// Sets the value of the `SO_BROADCAST` option for this socket.
1221     ///
1222     /// When enabled, this socket is allowed to send packets to a broadcast
1223     /// address.
set_broadcast(&self, on: bool) -> io::Result<()>1224     pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
1225         self.io.set_broadcast(on)
1226     }
1227 
1228     /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
1229     ///
1230     /// For more information about this option, see [`set_multicast_loop_v4`].
1231     ///
1232     /// [`set_multicast_loop_v4`]: method@Self::set_multicast_loop_v4
multicast_loop_v4(&self) -> io::Result<bool>1233     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
1234         self.io.multicast_loop_v4()
1235     }
1236 
1237     /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
1238     ///
1239     /// If enabled, multicast packets will be looped back to the local socket.
1240     ///
1241     /// # Note
1242     ///
1243     /// This may not have any affect on IPv6 sockets.
set_multicast_loop_v4(&self, on: bool) -> io::Result<()>1244     pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> {
1245         self.io.set_multicast_loop_v4(on)
1246     }
1247 
1248     /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
1249     ///
1250     /// For more information about this option, see [`set_multicast_ttl_v4`].
1251     ///
1252     /// [`set_multicast_ttl_v4`]: method@Self::set_multicast_ttl_v4
multicast_ttl_v4(&self) -> io::Result<u32>1253     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
1254         self.io.multicast_ttl_v4()
1255     }
1256 
1257     /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
1258     ///
1259     /// Indicates the time-to-live value of outgoing multicast packets for
1260     /// this socket. The default value is 1 which means that multicast packets
1261     /// don't leave the local network unless explicitly requested.
1262     ///
1263     /// # Note
1264     ///
1265     /// This may not have any affect on IPv6 sockets.
set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()>1266     pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> {
1267         self.io.set_multicast_ttl_v4(ttl)
1268     }
1269 
1270     /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1271     ///
1272     /// For more information about this option, see [`set_multicast_loop_v6`].
1273     ///
1274     /// [`set_multicast_loop_v6`]: method@Self::set_multicast_loop_v6
multicast_loop_v6(&self) -> io::Result<bool>1275     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
1276         self.io.multicast_loop_v6()
1277     }
1278 
1279     /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1280     ///
1281     /// Controls whether this socket sees the multicast packets it sends itself.
1282     ///
1283     /// # Note
1284     ///
1285     /// This may not have any affect on IPv4 sockets.
set_multicast_loop_v6(&self, on: bool) -> io::Result<()>1286     pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> {
1287         self.io.set_multicast_loop_v6(on)
1288     }
1289 
1290     /// Gets the value of the `IP_TTL` option for this socket.
1291     ///
1292     /// For more information about this option, see [`set_ttl`].
1293     ///
1294     /// [`set_ttl`]: method@Self::set_ttl
1295     ///
1296     /// # Examples
1297     ///
1298     /// ```no_run
1299     /// use tokio::net::UdpSocket;
1300     /// # use std::io;
1301     ///
1302     /// # async fn dox() -> io::Result<()> {
1303     /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
1304     ///
1305     /// println!("{:?}", sock.ttl()?);
1306     /// # Ok(())
1307     /// # }
1308     /// ```
ttl(&self) -> io::Result<u32>1309     pub fn ttl(&self) -> io::Result<u32> {
1310         self.io.ttl()
1311     }
1312 
1313     /// Sets the value for the `IP_TTL` option on this socket.
1314     ///
1315     /// This value sets the time-to-live field that is used in every packet sent
1316     /// from this socket.
1317     ///
1318     /// # Examples
1319     ///
1320     /// ```no_run
1321     /// use tokio::net::UdpSocket;
1322     /// # use std::io;
1323     ///
1324     /// # async fn dox() -> io::Result<()> {
1325     /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
1326     /// sock.set_ttl(60)?;
1327     ///
1328     /// # Ok(())
1329     /// # }
1330     /// ```
set_ttl(&self, ttl: u32) -> io::Result<()>1331     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
1332         self.io.set_ttl(ttl)
1333     }
1334 
1335     /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
1336     ///
1337     /// This function specifies a new multicast group for this socket to join.
1338     /// The address must be a valid multicast address, and `interface` is the
1339     /// address of the local interface with which the system should join the
1340     /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
1341     /// interface is chosen by the system.
join_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()>1342     pub fn join_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
1343         self.io.join_multicast_v4(&multiaddr, &interface)
1344     }
1345 
1346     /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
1347     ///
1348     /// This function specifies a new multicast group for this socket to join.
1349     /// The address must be a valid multicast address, and `interface` is the
1350     /// index of the interface to join/leave (or 0 to indicate any interface).
join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>1351     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
1352         self.io.join_multicast_v6(multiaddr, interface)
1353     }
1354 
1355     /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
1356     ///
1357     /// For more information about this option, see [`join_multicast_v4`].
1358     ///
1359     /// [`join_multicast_v4`]: method@Self::join_multicast_v4
leave_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()>1360     pub fn leave_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
1361         self.io.leave_multicast_v4(&multiaddr, &interface)
1362     }
1363 
1364     /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
1365     ///
1366     /// For more information about this option, see [`join_multicast_v6`].
1367     ///
1368     /// [`join_multicast_v6`]: method@Self::join_multicast_v6
leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>1369     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
1370         self.io.leave_multicast_v6(multiaddr, interface)
1371     }
1372 
1373     /// Returns the value of the `SO_ERROR` option.
1374     ///
1375     /// # Examples
1376     /// ```
1377     /// use tokio::net::UdpSocket;
1378     /// use std::io;
1379     ///
1380     /// #[tokio::main]
1381     /// async fn main() -> io::Result<()> {
1382     ///     // Create a socket
1383     ///     let socket = UdpSocket::bind("0.0.0.0:8080").await?;
1384     ///
1385     ///     if let Ok(Some(err)) = socket.take_error() {
1386     ///         println!("Got error: {:?}", err);
1387     ///     }
1388     ///
1389     ///     Ok(())
1390     /// }
1391     /// ```
take_error(&self) -> io::Result<Option<io::Error>>1392     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1393         self.io.take_error()
1394     }
1395 }
1396 
1397 impl TryFrom<std::net::UdpSocket> for UdpSocket {
1398     type Error = io::Error;
1399 
1400     /// Consumes stream, returning the tokio I/O object.
1401     ///
1402     /// This is equivalent to
1403     /// [`UdpSocket::from_std(stream)`](UdpSocket::from_std).
try_from(stream: std::net::UdpSocket) -> Result<Self, Self::Error>1404     fn try_from(stream: std::net::UdpSocket) -> Result<Self, Self::Error> {
1405         Self::from_std(stream)
1406     }
1407 }
1408 
1409 impl fmt::Debug for UdpSocket {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1410     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1411         self.io.fmt(f)
1412     }
1413 }
1414 
1415 #[cfg(all(unix))]
1416 mod sys {
1417     use super::UdpSocket;
1418     use std::os::unix::prelude::*;
1419 
1420     impl AsRawFd for UdpSocket {
as_raw_fd(&self) -> RawFd1421         fn as_raw_fd(&self) -> RawFd {
1422             self.io.as_raw_fd()
1423         }
1424     }
1425 }
1426 
1427 #[cfg(windows)]
1428 mod sys {
1429     use super::UdpSocket;
1430     use std::os::windows::prelude::*;
1431 
1432     impl AsRawSocket for UdpSocket {
as_raw_socket(&self) -> RawSocket1433         fn as_raw_socket(&self) -> RawSocket {
1434             self.io.as_raw_socket()
1435         }
1436     }
1437 }
1438