tokio/net/
udp.rs

1use crate::io::{Interest, PollEvented, ReadBuf, Ready};
2use crate::net::{to_socket_addrs, ToSocketAddrs};
3use crate::util::check_socket_for_blocking;
4
5use std::fmt;
6use std::io;
7use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr};
8use std::task::{ready, Context, Poll};
9
10cfg_io_util! {
11    use bytes::BufMut;
12}
13
14cfg_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
127impl UdpSocket {
128    /// This function will create a new UDP socket and attempt to bind it to
129    /// the `addr` provided.
130    ///
131    /// Binding with a port number of 0 will request that the OS assigns a port
132    /// to this listener. The port allocated can be queried via the `local_addr`
133    /// method.
134    ///
135    /// # Example
136    ///
137    /// ```no_run
138    /// use tokio::net::UdpSocket;
139    /// use std::io;
140    ///
141    /// #[tokio::main]
142    /// async fn main() -> io::Result<()> {
143    /// #   if cfg!(miri) { return Ok(()); } // No `socket` in miri.
144    ///     let sock = UdpSocket::bind("0.0.0.0:8080").await?;
145    ///     // use `sock`
146    /// #   let _ = sock;
147    ///     Ok(())
148    /// }
149    /// ```
150    pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
151        let addrs = to_socket_addrs(addr).await?;
152        let mut last_err = None;
153
154        for addr in addrs {
155            match UdpSocket::bind_addr(addr) {
156                Ok(socket) => return Ok(socket),
157                Err(e) => last_err = Some(e),
158            }
159        }
160
161        Err(last_err.unwrap_or_else(|| {
162            io::Error::new(
163                io::ErrorKind::InvalidInput,
164                "could not resolve to any address",
165            )
166        }))
167    }
168
169    fn bind_addr(addr: SocketAddr) -> io::Result<UdpSocket> {
170        let sys = mio::net::UdpSocket::bind(addr)?;
171        UdpSocket::new(sys)
172    }
173
174    #[track_caller]
175    fn new(socket: mio::net::UdpSocket) -> io::Result<UdpSocket> {
176        let io = PollEvented::new(socket)?;
177        Ok(UdpSocket { io })
178    }
179
180    /// Creates new `UdpSocket` from a previously bound `std::net::UdpSocket`.
181    ///
182    /// This function is intended to be used to wrap a UDP socket from the
183    /// standard library in the Tokio equivalent.
184    ///
185    /// This can be used in conjunction with `socket2`'s `Socket` interface to
186    /// configure a socket before it's handed off, such as setting options like
187    /// `reuse_address` or binding to multiple addresses.
188    ///
189    /// # Notes
190    ///
191    /// The caller is responsible for ensuring that the socket is in
192    /// non-blocking mode. Otherwise all I/O operations on the socket
193    /// will block the thread, which will cause unexpected behavior.
194    /// Non-blocking mode can be set using [`set_nonblocking`].
195    ///
196    /// Passing a listener in blocking mode is always erroneous,
197    /// and the behavior in that case may change in the future.
198    /// For example, it could panic.
199    ///
200    /// [`set_nonblocking`]: std::net::UdpSocket::set_nonblocking
201    ///
202    /// # Panics
203    ///
204    /// This function panics if thread-local runtime is not set.
205    ///
206    /// The runtime is usually set implicitly when this function is called
207    /// from a future driven by a tokio runtime, otherwise runtime can be set
208    /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
209    ///
210    /// # Example
211    ///
212    /// ```no_run
213    /// use tokio::net::UdpSocket;
214    /// # use std::{io, net::SocketAddr};
215    ///
216    /// # #[tokio::main]
217    /// # async fn main() -> io::Result<()> {
218    /// let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
219    /// let std_sock = std::net::UdpSocket::bind(addr)?;
220    /// std_sock.set_nonblocking(true)?;
221    /// let sock = UdpSocket::from_std(std_sock)?;
222    /// // use `sock`
223    /// # Ok(())
224    /// # }
225    /// ```
226    #[track_caller]
227    pub fn from_std(socket: net::UdpSocket) -> io::Result<UdpSocket> {
228        check_socket_for_blocking(&socket)?;
229
230        let io = mio::net::UdpSocket::from_std(socket);
231        UdpSocket::new(io)
232    }
233
234    /// Turns a [`tokio::net::UdpSocket`] into a [`std::net::UdpSocket`].
235    ///
236    /// The returned [`std::net::UdpSocket`] will have nonblocking mode set as
237    /// `true`.  Use [`set_nonblocking`] to change the blocking mode if needed.
238    ///
239    /// # Examples
240    ///
241    /// ```rust,no_run
242    /// use std::error::Error;
243    ///
244    /// #[tokio::main]
245    /// async fn main() -> Result<(), Box<dyn Error>> {
246    ///     let tokio_socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await?;
247    ///     let std_socket = tokio_socket.into_std()?;
248    ///     std_socket.set_nonblocking(false)?;
249    ///     Ok(())
250    /// }
251    /// ```
252    ///
253    /// [`tokio::net::UdpSocket`]: UdpSocket
254    /// [`std::net::UdpSocket`]: std::net::UdpSocket
255    /// [`set_nonblocking`]: fn@std::net::UdpSocket::set_nonblocking
256    pub fn into_std(self) -> io::Result<std::net::UdpSocket> {
257        #[cfg(unix)]
258        {
259            use std::os::unix::io::{FromRawFd, IntoRawFd};
260            self.io
261                .into_inner()
262                .map(IntoRawFd::into_raw_fd)
263                .map(|raw_fd| unsafe { std::net::UdpSocket::from_raw_fd(raw_fd) })
264        }
265
266        #[cfg(windows)]
267        {
268            use std::os::windows::io::{FromRawSocket, IntoRawSocket};
269            self.io
270                .into_inner()
271                .map(|io| io.into_raw_socket())
272                .map(|raw_socket| unsafe { std::net::UdpSocket::from_raw_socket(raw_socket) })
273        }
274    }
275
276    fn as_socket(&self) -> socket2::SockRef<'_> {
277        socket2::SockRef::from(self)
278    }
279
280    /// Returns the local address that this socket is bound to.
281    ///
282    /// # Example
283    ///
284    /// ```no_run
285    /// use tokio::net::UdpSocket;
286    /// # use std::{io, net::SocketAddr};
287    ///
288    /// # #[tokio::main]
289    /// # async fn main() -> io::Result<()> {
290    /// let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
291    /// let sock = UdpSocket::bind(addr).await?;
292    /// // the address the socket is bound to
293    /// let local_addr = sock.local_addr()?;
294    /// # Ok(())
295    /// # }
296    /// ```
297    pub fn local_addr(&self) -> io::Result<SocketAddr> {
298        self.io.local_addr()
299    }
300
301    /// Returns the socket address of the remote peer this socket was connected to.
302    ///
303    /// # Example
304    ///
305    /// ```
306    /// use tokio::net::UdpSocket;
307    ///
308    /// # use std::{io, net::SocketAddr};
309    /// # #[tokio::main]
310    /// # async fn main() -> io::Result<()> {
311    /// # if cfg!(miri) { return Ok(()); } // No `socket` in miri.
312    /// let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
313    /// let peer = "127.0.0.1:11100".parse::<SocketAddr>().unwrap();
314    /// let sock = UdpSocket::bind(addr).await?;
315    /// sock.connect(peer).await?;
316    /// assert_eq!(peer, sock.peer_addr()?);
317    /// #    Ok(())
318    /// # }
319    /// ```
320    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
321        self.io.peer_addr()
322    }
323
324    /// Connects the UDP socket setting the default destination for send() and
325    /// limiting packets that are read via `recv` from the address specified in
326    /// `addr`.
327    ///
328    /// # Example
329    ///
330    /// ```no_run
331    /// use tokio::net::UdpSocket;
332    /// # use std::{io, net::SocketAddr};
333    ///
334    /// # #[tokio::main]
335    /// # async fn main() -> io::Result<()> {
336    /// let sock = UdpSocket::bind("0.0.0.0:8080".parse::<SocketAddr>().unwrap()).await?;
337    ///
338    /// let remote_addr = "127.0.0.1:59600".parse::<SocketAddr>().unwrap();
339    /// sock.connect(remote_addr).await?;
340    /// let mut buf = [0u8; 32];
341    /// // recv from remote_addr
342    /// let len = sock.recv(&mut buf).await?;
343    /// // send to remote_addr
344    /// let _len = sock.send(&buf[..len]).await?;
345    /// # Ok(())
346    /// # }
347    /// ```
348    pub async fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
349        let addrs = to_socket_addrs(addr).await?;
350        let mut last_err = None;
351
352        for addr in addrs {
353            match self.io.connect(addr) {
354                Ok(()) => return Ok(()),
355                Err(e) => last_err = Some(e),
356            }
357        }
358
359        Err(last_err.unwrap_or_else(|| {
360            io::Error::new(
361                io::ErrorKind::InvalidInput,
362                "could not resolve to any address",
363            )
364        }))
365    }
366
367    /// Waits for any of the requested ready states.
368    ///
369    /// This function is usually paired with `try_recv()` or `try_send()`. It
370    /// can be used to concurrently `recv` / `send` to the same socket on a single
371    /// task without splitting the socket.
372    ///
373    /// The function may complete without the socket being ready. This is a
374    /// false-positive and attempting an operation will return with
375    /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
376    /// [`Ready`] set, so you should always check the returned value and possibly
377    /// wait again if the requested states are not set.
378    ///
379    /// # Cancel safety
380    ///
381    /// This method is cancel safe. Once a readiness event occurs, the method
382    /// will continue to return immediately until the readiness event is
383    /// consumed by an attempt to read or write that fails with `WouldBlock` or
384    /// `Poll::Pending`.
385    ///
386    /// # Examples
387    ///
388    /// Concurrently receive from and send to the socket on the same task
389    /// without splitting.
390    ///
391    /// ```no_run
392    /// use tokio::io::{self, Interest};
393    /// use tokio::net::UdpSocket;
394    ///
395    /// #[tokio::main]
396    /// async fn main() -> io::Result<()> {
397    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
398    ///     socket.connect("127.0.0.1:8081").await?;
399    ///
400    ///     loop {
401    ///         let ready = socket.ready(Interest::READABLE | Interest::WRITABLE).await?;
402    ///
403    ///         if ready.is_readable() {
404    ///             // The buffer is **not** included in the async task and will only exist
405    ///             // on the stack.
406    ///             let mut data = [0; 1024];
407    ///             match socket.try_recv(&mut data[..]) {
408    ///                 Ok(n) => {
409    ///                     println!("received {:?}", &data[..n]);
410    ///                 }
411    ///                 // False-positive, continue
412    ///                 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
413    ///                 Err(e) => {
414    ///                     return Err(e);
415    ///                 }
416    ///             }
417    ///         }
418    ///
419    ///         if ready.is_writable() {
420    ///             // Write some data
421    ///             match socket.try_send(b"hello world") {
422    ///                 Ok(n) => {
423    ///                     println!("sent {} bytes", n);
424    ///                 }
425    ///                 // False-positive, continue
426    ///                 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
427    ///                 Err(e) => {
428    ///                     return Err(e);
429    ///                 }
430    ///             }
431    ///         }
432    ///     }
433    /// }
434    /// ```
435    pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
436        let event = self.io.registration().readiness(interest).await?;
437        Ok(event.ready)
438    }
439
440    /// Waits for the socket to become writable.
441    ///
442    /// This function is equivalent to `ready(Interest::WRITABLE)` and is
443    /// usually paired with `try_send()` or `try_send_to()`.
444    ///
445    /// The function may complete without the socket being writable. This is a
446    /// false-positive and attempting a `try_send()` will return with
447    /// `io::ErrorKind::WouldBlock`.
448    ///
449    /// # Cancel safety
450    ///
451    /// This method is cancel safe. Once a readiness event occurs, the method
452    /// will continue to return immediately until the readiness event is
453    /// consumed by an attempt to write that fails with `WouldBlock` or
454    /// `Poll::Pending`.
455    ///
456    /// # Examples
457    ///
458    /// ```no_run
459    /// use tokio::net::UdpSocket;
460    /// use std::io;
461    ///
462    /// #[tokio::main]
463    /// async fn main() -> io::Result<()> {
464    ///     // Bind socket
465    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
466    ///     socket.connect("127.0.0.1:8081").await?;
467    ///
468    ///     loop {
469    ///         // Wait for the socket to be writable
470    ///         socket.writable().await?;
471    ///
472    ///         // Try to send data, this may still fail with `WouldBlock`
473    ///         // if the readiness event is a false positive.
474    ///         match socket.try_send(b"hello world") {
475    ///             Ok(n) => {
476    ///                 break;
477    ///             }
478    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
479    ///                 continue;
480    ///             }
481    ///             Err(e) => {
482    ///                 return Err(e);
483    ///             }
484    ///         }
485    ///     }
486    ///
487    ///     Ok(())
488    /// }
489    /// ```
490    pub async fn writable(&self) -> io::Result<()> {
491        self.ready(Interest::WRITABLE).await?;
492        Ok(())
493    }
494
495    /// Polls for write/send readiness.
496    ///
497    /// If the udp stream is not currently ready for sending, this method will
498    /// store a clone of the `Waker` from the provided `Context`. When the udp
499    /// stream becomes ready for sending, `Waker::wake` will be called on the
500    /// waker.
501    ///
502    /// Note that on multiple calls to `poll_send_ready` or `poll_send`, only
503    /// the `Waker` from the `Context` passed to the most recent call is
504    /// scheduled to receive a wakeup. (However, `poll_recv_ready` retains a
505    /// second, independent waker.)
506    ///
507    /// This function is intended for cases where creating and pinning a future
508    /// via [`writable`] is not feasible. Where possible, using [`writable`] is
509    /// preferred, as this supports polling from multiple tasks at once.
510    ///
511    /// # Return value
512    ///
513    /// The function returns:
514    ///
515    /// * `Poll::Pending` if the udp stream is not ready for writing.
516    /// * `Poll::Ready(Ok(()))` if the udp stream is ready for writing.
517    /// * `Poll::Ready(Err(e))` if an error is encountered.
518    ///
519    /// # Errors
520    ///
521    /// This function may encounter any standard I/O error except `WouldBlock`.
522    ///
523    /// [`writable`]: method@Self::writable
524    pub fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
525        self.io.registration().poll_write_ready(cx).map_ok(|_| ())
526    }
527
528    /// Sends data on the socket to the remote address that the socket is
529    /// connected to.
530    ///
531    /// The [`connect`] method will connect this socket to a remote address.
532    /// This method will fail if the socket is not connected.
533    ///
534    /// [`connect`]: method@Self::connect
535    ///
536    /// # Return
537    ///
538    /// On success, the number of bytes sent is returned, otherwise, the
539    /// encountered error is returned.
540    ///
541    /// # Cancel safety
542    ///
543    /// This method is cancel safe. If `send` is used as the event in a
544    /// [`tokio::select!`](crate::select) statement and some other branch
545    /// completes first, then it is guaranteed that the message was not sent.
546    ///
547    /// # Examples
548    ///
549    /// ```no_run
550    /// use tokio::io;
551    /// use tokio::net::UdpSocket;
552    ///
553    /// #[tokio::main]
554    /// async fn main() -> io::Result<()> {
555    ///     // Bind socket
556    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
557    ///     socket.connect("127.0.0.1:8081").await?;
558    ///
559    ///     // Send a message
560    ///     socket.send(b"hello world").await?;
561    ///
562    ///     Ok(())
563    /// }
564    /// ```
565    pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
566        self.io
567            .registration()
568            .async_io(Interest::WRITABLE, || self.io.send(buf))
569            .await
570    }
571
572    /// Attempts to send data on the socket to the remote address to which it
573    /// was previously `connect`ed.
574    ///
575    /// The [`connect`] method will connect this socket to a remote address.
576    /// This method will fail if the socket is not connected.
577    ///
578    /// Note that on multiple calls to a `poll_*` method in the send direction,
579    /// only the `Waker` from the `Context` passed to the most recent call will
580    /// be scheduled to receive a wakeup.
581    ///
582    /// # Return value
583    ///
584    /// The function returns:
585    ///
586    /// * `Poll::Pending` if the socket is not available to write
587    /// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent
588    /// * `Poll::Ready(Err(e))` if an error is encountered.
589    ///
590    /// # Errors
591    ///
592    /// This function may encounter any standard I/O error except `WouldBlock`.
593    ///
594    /// [`connect`]: method@Self::connect
595    pub fn poll_send(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
596        self.io
597            .registration()
598            .poll_write_io(cx, || self.io.send(buf))
599    }
600
601    /// Tries to send data on the socket to the remote address to which it is
602    /// connected.
603    ///
604    /// When the socket buffer is full, `Err(io::ErrorKind::WouldBlock)` is
605    /// returned. This function is usually paired with `writable()`.
606    ///
607    /// # Returns
608    ///
609    /// If successful, `Ok(n)` is returned, where `n` is the number of bytes
610    /// sent. If the socket is not ready to send data,
611    /// `Err(ErrorKind::WouldBlock)` is returned.
612    ///
613    /// # Examples
614    ///
615    /// ```no_run
616    /// use tokio::net::UdpSocket;
617    /// use std::io;
618    ///
619    /// #[tokio::main]
620    /// async fn main() -> io::Result<()> {
621    ///     // Bind a UDP socket
622    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
623    ///
624    ///     // Connect to a peer
625    ///     socket.connect("127.0.0.1:8081").await?;
626    ///
627    ///     loop {
628    ///         // Wait for the socket to be writable
629    ///         socket.writable().await?;
630    ///
631    ///         // Try to send data, this may still fail with `WouldBlock`
632    ///         // if the readiness event is a false positive.
633    ///         match socket.try_send(b"hello world") {
634    ///             Ok(n) => {
635    ///                 break;
636    ///             }
637    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
638    ///                 continue;
639    ///             }
640    ///             Err(e) => {
641    ///                 return Err(e);
642    ///             }
643    ///         }
644    ///     }
645    ///
646    ///     Ok(())
647    /// }
648    /// ```
649    pub fn try_send(&self, buf: &[u8]) -> io::Result<usize> {
650        self.io
651            .registration()
652            .try_io(Interest::WRITABLE, || self.io.send(buf))
653    }
654
655    /// Waits for the socket to become readable.
656    ///
657    /// This function is equivalent to `ready(Interest::READABLE)` and is usually
658    /// paired with `try_recv()`.
659    ///
660    /// The function may complete without the socket being readable. This is a
661    /// false-positive and attempting a `try_recv()` will return with
662    /// `io::ErrorKind::WouldBlock`.
663    ///
664    /// # Cancel safety
665    ///
666    /// This method is cancel safe. Once a readiness event occurs, the method
667    /// will continue to return immediately until the readiness event is
668    /// consumed by an attempt to read that fails with `WouldBlock` or
669    /// `Poll::Pending`.
670    ///
671    /// # Examples
672    ///
673    /// ```no_run
674    /// use tokio::net::UdpSocket;
675    /// use std::io;
676    ///
677    /// #[tokio::main]
678    /// async fn main() -> io::Result<()> {
679    ///     // Connect to a peer
680    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
681    ///     socket.connect("127.0.0.1:8081").await?;
682    ///
683    ///     loop {
684    ///         // Wait for the socket to be readable
685    ///         socket.readable().await?;
686    ///
687    ///         // The buffer is **not** included in the async task and will
688    ///         // only exist on the stack.
689    ///         let mut buf = [0; 1024];
690    ///
691    ///         // Try to recv data, this may still fail with `WouldBlock`
692    ///         // if the readiness event is a false positive.
693    ///         match socket.try_recv(&mut buf) {
694    ///             Ok(n) => {
695    ///                 println!("GOT {:?}", &buf[..n]);
696    ///                 break;
697    ///             }
698    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
699    ///                 continue;
700    ///             }
701    ///             Err(e) => {
702    ///                 return Err(e);
703    ///             }
704    ///         }
705    ///     }
706    ///
707    ///     Ok(())
708    /// }
709    /// ```
710    pub async fn readable(&self) -> io::Result<()> {
711        self.ready(Interest::READABLE).await?;
712        Ok(())
713    }
714
715    /// Polls for read/receive readiness.
716    ///
717    /// If the udp stream is not currently ready for receiving, this method will
718    /// store a clone of the `Waker` from the provided `Context`. When the udp
719    /// socket becomes ready for reading, `Waker::wake` will be called on the
720    /// waker.
721    ///
722    /// Note that on multiple calls to `poll_recv_ready`, `poll_recv` or
723    /// `poll_peek`, only the `Waker` from the `Context` passed to the most
724    /// recent call is scheduled to receive a wakeup. (However,
725    /// `poll_send_ready` retains a second, independent waker.)
726    ///
727    /// This function is intended for cases where creating and pinning a future
728    /// via [`readable`] is not feasible. Where possible, using [`readable`] is
729    /// preferred, as this supports polling from multiple tasks at once.
730    ///
731    /// # Return value
732    ///
733    /// The function returns:
734    ///
735    /// * `Poll::Pending` if the udp stream is not ready for reading.
736    /// * `Poll::Ready(Ok(()))` if the udp stream is ready for reading.
737    /// * `Poll::Ready(Err(e))` if an error is encountered.
738    ///
739    /// # Errors
740    ///
741    /// This function may encounter any standard I/O error except `WouldBlock`.
742    ///
743    /// [`readable`]: method@Self::readable
744    pub fn poll_recv_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
745        self.io.registration().poll_read_ready(cx).map_ok(|_| ())
746    }
747
748    /// Receives a single datagram message on the socket from the remote address
749    /// to which it is connected. On success, returns the number of bytes read.
750    ///
751    /// The function must be called with valid byte array `buf` of sufficient
752    /// size to hold the message bytes. If a message is too long to fit in the
753    /// supplied buffer, excess bytes may be discarded.
754    ///
755    /// The [`connect`] method will connect this socket to a remote address.
756    /// This method will fail if the socket is not connected.
757    ///
758    /// # Cancel safety
759    ///
760    /// This method is cancel safe. If `recv` is used as the event in a
761    /// [`tokio::select!`](crate::select) statement and some other branch
762    /// completes first, it is guaranteed that no messages were received on this
763    /// socket.
764    ///
765    /// [`connect`]: method@Self::connect
766    ///
767    /// ```no_run
768    /// use tokio::net::UdpSocket;
769    /// use std::io;
770    ///
771    /// #[tokio::main]
772    /// async fn main() -> io::Result<()> {
773    ///     // Bind socket
774    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
775    ///     socket.connect("127.0.0.1:8081").await?;
776    ///
777    ///     let mut buf = vec![0; 10];
778    ///     let n = socket.recv(&mut buf).await?;
779    ///
780    ///     println!("received {} bytes {:?}", n, &buf[..n]);
781    ///
782    ///     Ok(())
783    /// }
784    /// ```
785    pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
786        self.io
787            .registration()
788            .async_io(Interest::READABLE, || self.io.recv(buf))
789            .await
790    }
791
792    /// Attempts to receive a single datagram message on the socket from the remote
793    /// address to which it is `connect`ed.
794    ///
795    /// The [`connect`] method will connect this socket to a remote address. This method
796    /// resolves to an error if the socket is not connected.
797    ///
798    /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
799    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
800    /// receive a wakeup.
801    ///
802    /// # Return value
803    ///
804    /// The function returns:
805    ///
806    /// * `Poll::Pending` if the socket is not ready to read
807    /// * `Poll::Ready(Ok(()))` reads data `ReadBuf` if the socket is ready
808    /// * `Poll::Ready(Err(e))` if an error is encountered.
809    ///
810    /// # Errors
811    ///
812    /// This function may encounter any standard I/O error except `WouldBlock`.
813    ///
814    /// [`connect`]: method@Self::connect
815    pub fn poll_recv(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
816        #[allow(clippy::blocks_in_conditions)]
817        let n = ready!(self.io.registration().poll_read_io(cx, || {
818            // Safety: will not read the maybe uninitialized bytes.
819            let b = unsafe {
820                &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
821            };
822
823            self.io.recv(b)
824        }))?;
825
826        // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
827        unsafe {
828            buf.assume_init(n);
829        }
830        buf.advance(n);
831        Poll::Ready(Ok(()))
832    }
833
834    /// Tries to receive a single datagram message on the socket from the remote
835    /// address to which it is connected. On success, returns the number of
836    /// bytes read.
837    ///
838    /// This method must be called with valid byte array `buf` of sufficient size
839    /// to hold the message bytes. If a message is too long to fit in the
840    /// supplied buffer, excess bytes may be discarded.
841    ///
842    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
843    /// returned. This function is usually paired with `readable()`.
844    ///
845    /// # Examples
846    ///
847    /// ```no_run
848    /// use tokio::net::UdpSocket;
849    /// use std::io;
850    ///
851    /// #[tokio::main]
852    /// async fn main() -> io::Result<()> {
853    ///     // Connect to a peer
854    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
855    ///     socket.connect("127.0.0.1:8081").await?;
856    ///
857    ///     loop {
858    ///         // Wait for the socket to be readable
859    ///         socket.readable().await?;
860    ///
861    ///         // The buffer is **not** included in the async task and will
862    ///         // only exist on the stack.
863    ///         let mut buf = [0; 1024];
864    ///
865    ///         // Try to recv data, this may still fail with `WouldBlock`
866    ///         // if the readiness event is a false positive.
867    ///         match socket.try_recv(&mut buf) {
868    ///             Ok(n) => {
869    ///                 println!("GOT {:?}", &buf[..n]);
870    ///                 break;
871    ///             }
872    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
873    ///                 continue;
874    ///             }
875    ///             Err(e) => {
876    ///                 return Err(e);
877    ///             }
878    ///         }
879    ///     }
880    ///
881    ///     Ok(())
882    /// }
883    /// ```
884    pub fn try_recv(&self, buf: &mut [u8]) -> io::Result<usize> {
885        self.io
886            .registration()
887            .try_io(Interest::READABLE, || self.io.recv(buf))
888    }
889
890    cfg_io_util! {
891        /// Tries to receive data from the stream into the provided buffer, advancing the
892        /// buffer's internal cursor, returning how many bytes were read.
893        ///
894        /// This method must be called with valid byte array `buf` of sufficient size
895        /// to hold the message bytes. If a message is too long to fit in the
896        /// supplied buffer, excess bytes may be discarded.
897        ///
898        /// This method can be used even if `buf` is uninitialized.
899        ///
900        /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
901        /// returned. This function is usually paired with `readable()`.
902        ///
903        /// # Examples
904        ///
905        /// ```no_run
906        /// use tokio::net::UdpSocket;
907        /// use std::io;
908        ///
909        /// #[tokio::main]
910        /// async fn main() -> io::Result<()> {
911        ///     // Connect to a peer
912        ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
913        ///     socket.connect("127.0.0.1:8081").await?;
914        ///
915        ///     loop {
916        ///         // Wait for the socket to be readable
917        ///         socket.readable().await?;
918        ///
919        ///         let mut buf = Vec::with_capacity(1024);
920        ///
921        ///         // Try to recv data, this may still fail with `WouldBlock`
922        ///         // if the readiness event is a false positive.
923        ///         match socket.try_recv_buf(&mut buf) {
924        ///             Ok(n) => {
925        ///                 println!("GOT {:?}", &buf[..n]);
926        ///                 break;
927        ///             }
928        ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
929        ///                 continue;
930        ///             }
931        ///             Err(e) => {
932        ///                 return Err(e);
933        ///             }
934        ///         }
935        ///     }
936        ///
937        ///     Ok(())
938        /// }
939        /// ```
940        pub fn try_recv_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
941            self.io.registration().try_io(Interest::READABLE, || {
942                let dst = buf.chunk_mut();
943                let dst =
944                    unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
945
946                let n = (*self.io).recv(dst)?;
947
948                // Safety: We trust `UdpSocket::recv` to have filled up `n` bytes in the
949                // buffer.
950                unsafe {
951                    buf.advance_mut(n);
952                }
953
954                Ok(n)
955            })
956        }
957
958        /// Receives a single datagram message on the socket from the remote address
959        /// to which it is connected, advancing the buffer's internal cursor,
960        /// returning how many bytes were read.
961        ///
962        /// This method must be called with valid byte array `buf` of sufficient size
963        /// to hold the message bytes. If a message is too long to fit in the
964        /// supplied buffer, excess bytes may be discarded.
965        ///
966        /// This method can be used even if `buf` is uninitialized.
967        ///
968        /// # Examples
969        ///
970        /// ```no_run
971        /// use tokio::net::UdpSocket;
972        /// use std::io;
973        ///
974        /// #[tokio::main]
975        /// async fn main() -> io::Result<()> {
976        ///     // Connect to a peer
977        ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
978        ///     socket.connect("127.0.0.1:8081").await?;
979        ///
980        ///     let mut buf = Vec::with_capacity(512);
981        ///     let len = socket.recv_buf(&mut buf).await?;
982        ///
983        ///     println!("received {} bytes {:?}", len, &buf[..len]);
984        ///
985        ///     Ok(())
986        /// }
987        /// ```
988        pub async fn recv_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
989            self.io.registration().async_io(Interest::READABLE, || {
990                let dst = buf.chunk_mut();
991                let dst =
992                    unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
993
994                let n = (*self.io).recv(dst)?;
995
996                // Safety: We trust `UdpSocket::recv` to have filled up `n` bytes in the
997                // buffer.
998                unsafe {
999                    buf.advance_mut(n);
1000                }
1001
1002                Ok(n)
1003            }).await
1004        }
1005
1006        /// Tries to receive a single datagram message on the socket. On success,
1007        /// returns the number of bytes read and the origin.
1008        ///
1009        /// This method must be called with valid byte array `buf` of sufficient size
1010        /// to hold the message bytes. If a message is too long to fit in the
1011        /// supplied buffer, excess bytes may be discarded.
1012        ///
1013        /// This method can be used even if `buf` is uninitialized.
1014        ///
1015        /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1016        /// returned. This function is usually paired with `readable()`.
1017        ///
1018        /// # Notes
1019        /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1020        /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1021        /// Because UDP is stateless and does not validate the origin of a packet,
1022        /// the attacker does not need to be able to intercept traffic in order to interfere.
1023        /// It is important to be aware of this when designing your application-level protocol.
1024        ///
1025        /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1026        ///
1027        /// # Examples
1028        ///
1029        /// ```no_run
1030        /// use tokio::net::UdpSocket;
1031        /// use std::io;
1032        ///
1033        /// #[tokio::main]
1034        /// async fn main() -> io::Result<()> {
1035        ///     // Connect to a peer
1036        ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1037        ///
1038        ///     loop {
1039        ///         // Wait for the socket to be readable
1040        ///         socket.readable().await?;
1041        ///
1042        ///         let mut buf = Vec::with_capacity(1024);
1043        ///
1044        ///         // Try to recv data, this may still fail with `WouldBlock`
1045        ///         // if the readiness event is a false positive.
1046        ///         match socket.try_recv_buf_from(&mut buf) {
1047        ///             Ok((n, _addr)) => {
1048        ///                 println!("GOT {:?}", &buf[..n]);
1049        ///                 break;
1050        ///             }
1051        ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1052        ///                 continue;
1053        ///             }
1054        ///             Err(e) => {
1055        ///                 return Err(e);
1056        ///             }
1057        ///         }
1058        ///     }
1059        ///
1060        ///     Ok(())
1061        /// }
1062        /// ```
1063        pub fn try_recv_buf_from<B: BufMut>(&self, buf: &mut B) -> io::Result<(usize, SocketAddr)> {
1064            self.io.registration().try_io(Interest::READABLE, || {
1065                let dst = buf.chunk_mut();
1066                let dst =
1067                    unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
1068
1069                let (n, addr) = (*self.io).recv_from(dst)?;
1070
1071                // Safety: We trust `UdpSocket::recv_from` to have filled up `n` bytes in the
1072                // buffer.
1073                unsafe {
1074                    buf.advance_mut(n);
1075                }
1076
1077                Ok((n, addr))
1078            })
1079        }
1080
1081        /// Receives a single datagram message on the socket, advancing the
1082        /// buffer's internal cursor, returning how many bytes were read and the origin.
1083        ///
1084        /// This method must be called with valid byte array `buf` of sufficient size
1085        /// to hold the message bytes. If a message is too long to fit in the
1086        /// supplied buffer, excess bytes may be discarded.
1087        ///
1088        /// This method can be used even if `buf` is uninitialized.
1089        ///
1090        /// # Notes
1091        /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1092        /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1093        /// Because UDP is stateless and does not validate the origin of a packet,
1094        /// the attacker does not need to be able to intercept traffic in order to interfere.
1095        /// It is important to be aware of this when designing your application-level protocol.
1096        ///
1097        /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1098        ///
1099        /// # Examples
1100        ///
1101        /// ```no_run
1102        /// use tokio::net::UdpSocket;
1103        /// use std::io;
1104        ///
1105        /// #[tokio::main]
1106        /// async fn main() -> io::Result<()> {
1107        ///     // Connect to a peer
1108        ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1109        ///     socket.connect("127.0.0.1:8081").await?;
1110        ///
1111        ///     let mut buf = Vec::with_capacity(512);
1112        ///     let (len, addr) = socket.recv_buf_from(&mut buf).await?;
1113        ///
1114        ///     println!("received {:?} bytes from {:?}", len, addr);
1115        ///
1116        ///     Ok(())
1117        /// }
1118        /// ```
1119        pub async fn recv_buf_from<B: BufMut>(&self, buf: &mut B) -> io::Result<(usize, SocketAddr)> {
1120            self.io.registration().async_io(Interest::READABLE, || {
1121                let dst = buf.chunk_mut();
1122                let dst =
1123                    unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
1124
1125                let (n, addr) = (*self.io).recv_from(dst)?;
1126
1127                // Safety: We trust `UdpSocket::recv_from` to have filled up `n` bytes in the
1128                // buffer.
1129                unsafe {
1130                    buf.advance_mut(n);
1131                }
1132
1133                Ok((n,addr))
1134            }).await
1135        }
1136    }
1137
1138    /// Sends data on the socket to the given address. On success, returns the
1139    /// number of bytes written.
1140    ///
1141    /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
1142    /// documentation for concrete examples.
1143    ///
1144    /// It is possible for `addr` to yield multiple addresses, but `send_to`
1145    /// will only send data to the first address yielded by `addr`.
1146    ///
1147    /// This will return an error when the IP version of the local socket does
1148    /// not match that returned from [`ToSocketAddrs`].
1149    ///
1150    /// [`ToSocketAddrs`]: crate::net::ToSocketAddrs
1151    ///
1152    /// # Cancel safety
1153    ///
1154    /// This method is cancel safe. If `send_to` is used as the event in a
1155    /// [`tokio::select!`](crate::select) statement and some other branch
1156    /// completes first, then it is guaranteed that the message was not sent.
1157    ///
1158    /// # Example
1159    ///
1160    /// ```no_run
1161    /// use tokio::net::UdpSocket;
1162    /// use std::io;
1163    ///
1164    /// #[tokio::main]
1165    /// async fn main() -> io::Result<()> {
1166    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1167    ///     let len = socket.send_to(b"hello world", "127.0.0.1:8081").await?;
1168    ///
1169    ///     println!("Sent {} bytes", len);
1170    ///
1171    ///     Ok(())
1172    /// }
1173    /// ```
1174    pub async fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
1175        let mut addrs = to_socket_addrs(addr).await?;
1176
1177        match addrs.next() {
1178            Some(target) => self.send_to_addr(buf, target).await,
1179            None => Err(io::Error::new(
1180                io::ErrorKind::InvalidInput,
1181                "no addresses to send data to",
1182            )),
1183        }
1184    }
1185
1186    /// Attempts to send data on the socket to a given address.
1187    ///
1188    /// Note that on multiple calls to a `poll_*` method in the send direction, only the
1189    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1190    /// receive a wakeup.
1191    ///
1192    /// # Return value
1193    ///
1194    /// The function returns:
1195    ///
1196    /// * `Poll::Pending` if the socket is not ready to write
1197    /// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent.
1198    /// * `Poll::Ready(Err(e))` if an error is encountered.
1199    ///
1200    /// # Errors
1201    ///
1202    /// This function may encounter any standard I/O error except `WouldBlock`.
1203    pub fn poll_send_to(
1204        &self,
1205        cx: &mut Context<'_>,
1206        buf: &[u8],
1207        target: SocketAddr,
1208    ) -> Poll<io::Result<usize>> {
1209        self.io
1210            .registration()
1211            .poll_write_io(cx, || self.io.send_to(buf, target))
1212    }
1213
1214    /// Tries to send data on the socket to the given address, but if the send is
1215    /// blocked this will return right away.
1216    ///
1217    /// This function is usually paired with `writable()`.
1218    ///
1219    /// # Returns
1220    ///
1221    /// If successful, returns the number of bytes sent
1222    ///
1223    /// Users should ensure that when the remote cannot receive, the
1224    /// [`ErrorKind::WouldBlock`] is properly handled. An error can also occur
1225    /// if the IP version of the socket does not match that of `target`.
1226    ///
1227    /// [`ErrorKind::WouldBlock`]: std::io::ErrorKind::WouldBlock
1228    ///
1229    /// # Example
1230    ///
1231    /// ```no_run
1232    /// use tokio::net::UdpSocket;
1233    /// use std::error::Error;
1234    /// use std::io;
1235    ///
1236    /// #[tokio::main]
1237    /// async fn main() -> Result<(), Box<dyn Error>> {
1238    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1239    ///
1240    ///     let dst = "127.0.0.1:8081".parse()?;
1241    ///
1242    ///     loop {
1243    ///         socket.writable().await?;
1244    ///
1245    ///         match socket.try_send_to(&b"hello world"[..], dst) {
1246    ///             Ok(sent) => {
1247    ///                 println!("sent {} bytes", sent);
1248    ///                 break;
1249    ///             }
1250    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1251    ///                 // Writable false positive.
1252    ///                 continue;
1253    ///             }
1254    ///             Err(e) => return Err(e.into()),
1255    ///         }
1256    ///     }
1257    ///
1258    ///     Ok(())
1259    /// }
1260    /// ```
1261    pub fn try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
1262        self.io
1263            .registration()
1264            .try_io(Interest::WRITABLE, || self.io.send_to(buf, target))
1265    }
1266
1267    async fn send_to_addr(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
1268        self.io
1269            .registration()
1270            .async_io(Interest::WRITABLE, || self.io.send_to(buf, target))
1271            .await
1272    }
1273
1274    /// Receives a single datagram message on the socket. On success, returns
1275    /// the number of bytes read and the origin.
1276    ///
1277    /// The function must be called with valid byte array `buf` of sufficient
1278    /// size to hold the message bytes. If a message is too long to fit in the
1279    /// supplied buffer, excess bytes may be discarded.
1280    ///
1281    /// # Cancel safety
1282    ///
1283    /// This method is cancel safe. If `recv_from` is used as the event in a
1284    /// [`tokio::select!`](crate::select) statement and some other branch
1285    /// completes first, it is guaranteed that no messages were received on this
1286    /// socket.
1287    ///
1288    /// # Example
1289    ///
1290    /// ```no_run
1291    /// use tokio::net::UdpSocket;
1292    /// use std::io;
1293    ///
1294    /// #[tokio::main]
1295    /// async fn main() -> io::Result<()> {
1296    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1297    ///
1298    ///     let mut buf = vec![0u8; 32];
1299    ///     let (len, addr) = socket.recv_from(&mut buf).await?;
1300    ///
1301    ///     println!("received {:?} bytes from {:?}", len, addr);
1302    ///
1303    ///     Ok(())
1304    /// }
1305    /// ```
1306    ///
1307    /// # Notes
1308    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1309    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1310    /// Because UDP is stateless and does not validate the origin of a packet,
1311    /// the attacker does not need to be able to intercept traffic in order to interfere.
1312    /// It is important to be aware of this when designing your application-level protocol.
1313    ///
1314    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1315    pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1316        self.io
1317            .registration()
1318            .async_io(Interest::READABLE, || self.io.recv_from(buf))
1319            .await
1320    }
1321
1322    /// Attempts to receive a single datagram on the socket.
1323    ///
1324    /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1325    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1326    /// receive a wakeup.
1327    ///
1328    /// # Return value
1329    ///
1330    /// The function returns:
1331    ///
1332    /// * `Poll::Pending` if the socket is not ready to read
1333    /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1334    /// * `Poll::Ready(Err(e))` if an error is encountered.
1335    ///
1336    /// # Errors
1337    ///
1338    /// This function may encounter any standard I/O error except `WouldBlock`.
1339    ///
1340    /// # Notes
1341    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1342    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1343    /// Because UDP is stateless and does not validate the origin of a packet,
1344    /// the attacker does not need to be able to intercept traffic in order to interfere.
1345    /// It is important to be aware of this when designing your application-level protocol.
1346    ///
1347    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1348    pub fn poll_recv_from(
1349        &self,
1350        cx: &mut Context<'_>,
1351        buf: &mut ReadBuf<'_>,
1352    ) -> Poll<io::Result<SocketAddr>> {
1353        #[allow(clippy::blocks_in_conditions)]
1354        let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1355            // Safety: will not read the maybe uninitialized bytes.
1356            let b = unsafe {
1357                &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1358            };
1359
1360            self.io.recv_from(b)
1361        }))?;
1362
1363        // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1364        unsafe {
1365            buf.assume_init(n);
1366        }
1367        buf.advance(n);
1368        Poll::Ready(Ok(addr))
1369    }
1370
1371    /// Tries to receive a single datagram message on the socket. On success,
1372    /// returns the number of bytes read and the origin.
1373    ///
1374    /// This method must be called with valid byte array `buf` of sufficient size
1375    /// to hold the message bytes. If a message is too long to fit in the
1376    /// supplied buffer, excess bytes may be discarded.
1377    ///
1378    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1379    /// returned. This function is usually paired with `readable()`.
1380    ///
1381    /// # Notes
1382    ///
1383    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1384    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1385    /// Because UDP is stateless and does not validate the origin of a packet,
1386    /// the attacker does not need to be able to intercept traffic in order to interfere.
1387    /// It is important to be aware of this when designing your application-level protocol.
1388    ///
1389    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1390    ///
1391    /// # Examples
1392    ///
1393    /// ```no_run
1394    /// use tokio::net::UdpSocket;
1395    /// use std::io;
1396    ///
1397    /// #[tokio::main]
1398    /// async fn main() -> io::Result<()> {
1399    ///     // Connect to a peer
1400    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1401    ///
1402    ///     loop {
1403    ///         // Wait for the socket to be readable
1404    ///         socket.readable().await?;
1405    ///
1406    ///         // The buffer is **not** included in the async task and will
1407    ///         // only exist on the stack.
1408    ///         let mut buf = [0; 1024];
1409    ///
1410    ///         // Try to recv data, this may still fail with `WouldBlock`
1411    ///         // if the readiness event is a false positive.
1412    ///         match socket.try_recv_from(&mut buf) {
1413    ///             Ok((n, _addr)) => {
1414    ///                 println!("GOT {:?}", &buf[..n]);
1415    ///                 break;
1416    ///             }
1417    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1418    ///                 continue;
1419    ///             }
1420    ///             Err(e) => {
1421    ///                 return Err(e);
1422    ///             }
1423    ///         }
1424    ///     }
1425    ///
1426    ///     Ok(())
1427    /// }
1428    /// ```
1429    pub fn try_recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1430        self.io
1431            .registration()
1432            .try_io(Interest::READABLE, || self.io.recv_from(buf))
1433    }
1434
1435    /// Tries to read or write from the socket using a user-provided IO operation.
1436    ///
1437    /// If the socket is ready, the provided closure is called. The closure
1438    /// should attempt to perform IO operation on the socket by manually
1439    /// calling the appropriate syscall. If the operation fails because the
1440    /// socket is not actually ready, then the closure should return a
1441    /// `WouldBlock` error and the readiness flag is cleared. The return value
1442    /// of the closure is then returned by `try_io`.
1443    ///
1444    /// If the socket is not ready, then the closure is not called
1445    /// and a `WouldBlock` error is returned.
1446    ///
1447    /// The closure should only return a `WouldBlock` error if it has performed
1448    /// an IO operation on the socket that failed due to the socket not being
1449    /// ready. Returning a `WouldBlock` error in any other situation will
1450    /// incorrectly clear the readiness flag, which can cause the socket to
1451    /// behave incorrectly.
1452    ///
1453    /// The closure should not perform the IO operation using any of the methods
1454    /// defined on the Tokio `UdpSocket` type, as this will mess with the
1455    /// readiness flag and can cause the socket to behave incorrectly.
1456    ///
1457    /// This method is not intended to be used with combined interests.
1458    /// The closure should perform only one type of IO operation, so it should not
1459    /// require more than one ready state. This method may panic or sleep forever
1460    /// if it is called with a combined interest.
1461    ///
1462    /// Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.
1463    ///
1464    /// [`readable()`]: UdpSocket::readable()
1465    /// [`writable()`]: UdpSocket::writable()
1466    /// [`ready()`]: UdpSocket::ready()
1467    pub fn try_io<R>(
1468        &self,
1469        interest: Interest,
1470        f: impl FnOnce() -> io::Result<R>,
1471    ) -> io::Result<R> {
1472        self.io
1473            .registration()
1474            .try_io(interest, || self.io.try_io(f))
1475    }
1476
1477    /// Reads or writes from the socket using a user-provided IO operation.
1478    ///
1479    /// The readiness of the socket is awaited and when the socket is ready,
1480    /// the provided closure is called. The closure should attempt to perform
1481    /// IO operation on the socket by manually calling the appropriate syscall.
1482    /// If the operation fails because the socket is not actually ready,
1483    /// then the closure should return a `WouldBlock` error. In such case the
1484    /// readiness flag is cleared and the socket readiness is awaited again.
1485    /// This loop is repeated until the closure returns an `Ok` or an error
1486    /// other than `WouldBlock`.
1487    ///
1488    /// The closure should only return a `WouldBlock` error if it has performed
1489    /// an IO operation on the socket that failed due to the socket not being
1490    /// ready. Returning a `WouldBlock` error in any other situation will
1491    /// incorrectly clear the readiness flag, which can cause the socket to
1492    /// behave incorrectly.
1493    ///
1494    /// The closure should not perform the IO operation using any of the methods
1495    /// defined on the Tokio `UdpSocket` type, as this will mess with the
1496    /// readiness flag and can cause the socket to behave incorrectly.
1497    ///
1498    /// This method is not intended to be used with combined interests.
1499    /// The closure should perform only one type of IO operation, so it should not
1500    /// require more than one ready state. This method may panic or sleep forever
1501    /// if it is called with a combined interest.
1502    pub async fn async_io<R>(
1503        &self,
1504        interest: Interest,
1505        mut f: impl FnMut() -> io::Result<R>,
1506    ) -> io::Result<R> {
1507        self.io
1508            .registration()
1509            .async_io(interest, || self.io.try_io(&mut f))
1510            .await
1511    }
1512
1513    /// Receives a single datagram from the connected address without removing it from the queue.
1514    /// On success, returns the number of bytes read from whence the data came.
1515    ///
1516    /// # Notes
1517    ///
1518    /// On Windows, if the data is larger than the buffer specified, the buffer
1519    /// is filled with the first part of the data, and peek returns the error
1520    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1521    /// Make sure to always use a sufficiently large buffer to hold the
1522    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1523    ///
1524    /// MacOS will return an error if you pass a zero-sized buffer.
1525    ///
1526    /// If you're merely interested in learning the sender of the data at the head of the queue,
1527    /// try [`peek_sender`].
1528    ///
1529    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1530    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1531    /// Because UDP is stateless and does not validate the origin of a packet,
1532    /// the attacker does not need to be able to intercept traffic in order to interfere.
1533    /// It is important to be aware of this when designing your application-level protocol.
1534    ///
1535    /// # Examples
1536    ///
1537    /// ```no_run
1538    /// use tokio::net::UdpSocket;
1539    /// use std::io;
1540    ///
1541    /// #[tokio::main]
1542    /// async fn main() -> io::Result<()> {
1543    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1544    ///
1545    ///     let mut buf = vec![0u8; 32];
1546    ///     let len = socket.peek(&mut buf).await?;
1547    ///
1548    ///     println!("peeked {:?} bytes", len);
1549    ///
1550    ///     Ok(())
1551    /// }
1552    /// ```
1553    ///
1554    /// [`peek_sender`]: method@Self::peek_sender
1555    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1556    pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1557        self.io
1558            .registration()
1559            .async_io(Interest::READABLE, || self.io.peek(buf))
1560            .await
1561    }
1562
1563    /// Receives data from the connected address, without removing it from the input queue.
1564    ///
1565    /// # Notes
1566    ///
1567    /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1568    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1569    /// receive a wakeup
1570    ///
1571    /// On Windows, if the data is larger than the buffer specified, the buffer
1572    /// is filled with the first part of the data, and peek returns the error
1573    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1574    /// Make sure to always use a sufficiently large buffer to hold the
1575    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1576    ///
1577    /// MacOS will return an error if you pass a zero-sized buffer.
1578    ///
1579    /// If you're merely interested in learning the sender of the data at the head of the queue,
1580    /// try [`poll_peek_sender`].
1581    ///
1582    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1583    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1584    /// Because UDP is stateless and does not validate the origin of a packet,
1585    /// the attacker does not need to be able to intercept traffic in order to interfere.
1586    /// It is important to be aware of this when designing your application-level protocol.
1587    ///
1588    /// # Return value
1589    ///
1590    /// The function returns:
1591    ///
1592    /// * `Poll::Pending` if the socket is not ready to read
1593    /// * `Poll::Ready(Ok(()))` reads data into `ReadBuf` if the socket is ready
1594    /// * `Poll::Ready(Err(e))` if an error is encountered.
1595    ///
1596    /// # Errors
1597    ///
1598    /// This function may encounter any standard I/O error except `WouldBlock`.
1599    ///
1600    /// [`poll_peek_sender`]: method@Self::poll_peek_sender
1601    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1602    pub fn poll_peek(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
1603        #[allow(clippy::blocks_in_conditions)]
1604        let n = ready!(self.io.registration().poll_read_io(cx, || {
1605            // Safety: will not read the maybe uninitialized bytes.
1606            let b = unsafe {
1607                &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1608            };
1609
1610            self.io.peek(b)
1611        }))?;
1612
1613        // Safety: We trust `peek` to have filled up `n` bytes in the buffer.
1614        unsafe {
1615            buf.assume_init(n);
1616        }
1617        buf.advance(n);
1618        Poll::Ready(Ok(()))
1619    }
1620
1621    /// Tries to receive data on the connected address without removing it from the input queue.
1622    /// On success, returns the number of bytes read.
1623    ///
1624    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1625    /// returned. This function is usually paired with `readable()`.
1626    ///
1627    /// # Notes
1628    ///
1629    /// On Windows, if the data is larger than the buffer specified, the buffer
1630    /// is filled with the first part of the data, and peek returns the error
1631    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1632    /// Make sure to always use a sufficiently large buffer to hold the
1633    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1634    ///
1635    /// MacOS will return an error if you pass a zero-sized buffer.
1636    ///
1637    /// If you're merely interested in learning the sender of the data at the head of the queue,
1638    /// try [`try_peek_sender`].
1639    ///
1640    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1641    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1642    /// Because UDP is stateless and does not validate the origin of a packet,
1643    /// the attacker does not need to be able to intercept traffic in order to interfere.
1644    /// It is important to be aware of this when designing your application-level protocol.
1645    ///
1646    /// [`try_peek_sender`]: method@Self::try_peek_sender
1647    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1648    pub fn try_peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1649        self.io
1650            .registration()
1651            .try_io(Interest::READABLE, || self.io.peek(buf))
1652    }
1653
1654    /// Receives data from the socket, without removing it from the input queue.
1655    /// On success, returns the number of bytes read and the address from whence
1656    /// the data came.
1657    ///
1658    /// # Notes
1659    ///
1660    /// On Windows, if the data is larger than the buffer specified, the buffer
1661    /// is filled with the first part of the data, and `peek_from` returns the error
1662    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1663    /// Make sure to always use a sufficiently large buffer to hold the
1664    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1665    ///
1666    /// MacOS will return an error if you pass a zero-sized buffer.
1667    ///
1668    /// If you're merely interested in learning the sender of the data at the head of the queue,
1669    /// try [`peek_sender`].
1670    ///
1671    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1672    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1673    /// Because UDP is stateless and does not validate the origin of a packet,
1674    /// the attacker does not need to be able to intercept traffic in order to interfere.
1675    /// It is important to be aware of this when designing your application-level protocol.
1676    ///
1677    /// # Examples
1678    ///
1679    /// ```no_run
1680    /// use tokio::net::UdpSocket;
1681    /// use std::io;
1682    ///
1683    /// #[tokio::main]
1684    /// async fn main() -> io::Result<()> {
1685    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1686    ///
1687    ///     let mut buf = vec![0u8; 32];
1688    ///     let (len, addr) = socket.peek_from(&mut buf).await?;
1689    ///
1690    ///     println!("peeked {:?} bytes from {:?}", len, addr);
1691    ///
1692    ///     Ok(())
1693    /// }
1694    /// ```
1695    ///
1696    /// [`peek_sender`]: method@Self::peek_sender
1697    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1698    pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1699        self.io
1700            .registration()
1701            .async_io(Interest::READABLE, || self.io.peek_from(buf))
1702            .await
1703    }
1704
1705    /// Receives data from the socket, without removing it from the input queue.
1706    /// On success, returns the sending address of the datagram.
1707    ///
1708    /// # Notes
1709    ///
1710    /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1711    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1712    /// receive a wakeup
1713    ///
1714    /// On Windows, if the data is larger than the buffer specified, the buffer
1715    /// is filled with the first part of the data, and peek returns the error
1716    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1717    /// Make sure to always use a sufficiently large buffer to hold the
1718    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1719    ///
1720    /// MacOS will return an error if you pass a zero-sized buffer.
1721    ///
1722    /// If you're merely interested in learning the sender of the data at the head of the queue,
1723    /// try [`poll_peek_sender`].
1724    ///
1725    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1726    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1727    /// Because UDP is stateless and does not validate the origin of a packet,
1728    /// the attacker does not need to be able to intercept traffic in order to interfere.
1729    /// It is important to be aware of this when designing your application-level protocol.
1730    ///
1731    /// # Return value
1732    ///
1733    /// The function returns:
1734    ///
1735    /// * `Poll::Pending` if the socket is not ready to read
1736    /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1737    /// * `Poll::Ready(Err(e))` if an error is encountered.
1738    ///
1739    /// # Errors
1740    ///
1741    /// This function may encounter any standard I/O error except `WouldBlock`.
1742    ///
1743    /// [`poll_peek_sender`]: method@Self::poll_peek_sender
1744    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1745    pub fn poll_peek_from(
1746        &self,
1747        cx: &mut Context<'_>,
1748        buf: &mut ReadBuf<'_>,
1749    ) -> Poll<io::Result<SocketAddr>> {
1750        #[allow(clippy::blocks_in_conditions)]
1751        let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1752            // Safety: will not read the maybe uninitialized bytes.
1753            let b = unsafe {
1754                &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1755            };
1756
1757            self.io.peek_from(b)
1758        }))?;
1759
1760        // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1761        unsafe {
1762            buf.assume_init(n);
1763        }
1764        buf.advance(n);
1765        Poll::Ready(Ok(addr))
1766    }
1767
1768    /// Tries to receive data on the socket without removing it from the input queue.
1769    /// On success, returns the number of bytes read and the sending address of the
1770    /// datagram.
1771    ///
1772    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1773    /// returned. This function is usually paired with `readable()`.
1774    ///
1775    /// # Notes
1776    ///
1777    /// On Windows, if the data is larger than the buffer specified, the buffer
1778    /// is filled with the first part of the data, and peek returns the error
1779    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1780    /// Make sure to always use a sufficiently large buffer to hold the
1781    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1782    ///
1783    /// MacOS will return an error if you pass a zero-sized buffer.
1784    ///
1785    /// If you're merely interested in learning the sender of the data at the head of the queue,
1786    /// try [`try_peek_sender`].
1787    ///
1788    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1789    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1790    /// Because UDP is stateless and does not validate the origin of a packet,
1791    /// the attacker does not need to be able to intercept traffic in order to interfere.
1792    /// It is important to be aware of this when designing your application-level protocol.
1793    ///
1794    /// [`try_peek_sender`]: method@Self::try_peek_sender
1795    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1796    pub fn try_peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1797        self.io
1798            .registration()
1799            .try_io(Interest::READABLE, || self.io.peek_from(buf))
1800    }
1801
1802    /// Retrieve the sender of the data at the head of the input queue, waiting if empty.
1803    ///
1804    /// This is equivalent to calling [`peek_from`] with a zero-sized buffer,
1805    /// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
1806    ///
1807    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1808    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1809    /// Because UDP is stateless and does not validate the origin of a packet,
1810    /// the attacker does not need to be able to intercept traffic in order to interfere.
1811    /// It is important to be aware of this when designing your application-level protocol.
1812    ///
1813    /// [`peek_from`]: method@Self::peek_from
1814    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1815    pub async fn peek_sender(&self) -> io::Result<SocketAddr> {
1816        self.io
1817            .registration()
1818            .async_io(Interest::READABLE, || self.peek_sender_inner())
1819            .await
1820    }
1821
1822    /// Retrieve the sender of the data at the head of the input queue,
1823    /// scheduling a wakeup if empty.
1824    ///
1825    /// This is equivalent to calling [`poll_peek_from`] with a zero-sized buffer,
1826    /// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
1827    ///
1828    /// # Notes
1829    ///
1830    /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1831    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1832    /// receive a wakeup.
1833    ///
1834    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1835    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1836    /// Because UDP is stateless and does not validate the origin of a packet,
1837    /// the attacker does not need to be able to intercept traffic in order to interfere.
1838    /// It is important to be aware of this when designing your application-level protocol.
1839    ///
1840    /// [`poll_peek_from`]: method@Self::poll_peek_from
1841    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1842    pub fn poll_peek_sender(&self, cx: &mut Context<'_>) -> Poll<io::Result<SocketAddr>> {
1843        self.io
1844            .registration()
1845            .poll_read_io(cx, || self.peek_sender_inner())
1846    }
1847
1848    /// Try to retrieve the sender of the data at the head of the input queue.
1849    ///
1850    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1851    /// returned. This function is usually paired with `readable()`.
1852    ///
1853    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1854    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1855    /// Because UDP is stateless and does not validate the origin of a packet,
1856    /// the attacker does not need to be able to intercept traffic in order to interfere.
1857    /// It is important to be aware of this when designing your application-level protocol.
1858    ///
1859    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1860    pub fn try_peek_sender(&self) -> io::Result<SocketAddr> {
1861        self.io
1862            .registration()
1863            .try_io(Interest::READABLE, || self.peek_sender_inner())
1864    }
1865
1866    #[inline]
1867    fn peek_sender_inner(&self) -> io::Result<SocketAddr> {
1868        self.io.try_io(|| {
1869            self.as_socket()
1870                .peek_sender()?
1871                // May be `None` if the platform doesn't populate the sender for some reason.
1872                // In testing, that only occurred on macOS if you pass a zero-sized buffer,
1873                // but the implementation of `Socket::peek_sender()` covers that.
1874                .as_socket()
1875                .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "sender not available"))
1876        })
1877    }
1878
1879    /// Gets the value of the `SO_BROADCAST` option for this socket.
1880    ///
1881    /// For more information about this option, see [`set_broadcast`].
1882    ///
1883    /// [`set_broadcast`]: method@Self::set_broadcast
1884    pub fn broadcast(&self) -> io::Result<bool> {
1885        self.io.broadcast()
1886    }
1887
1888    /// Sets the value of the `SO_BROADCAST` option for this socket.
1889    ///
1890    /// When enabled, this socket is allowed to send packets to a broadcast
1891    /// address.
1892    pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
1893        self.io.set_broadcast(on)
1894    }
1895
1896    /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
1897    ///
1898    /// For more information about this option, see [`set_multicast_loop_v4`].
1899    ///
1900    /// [`set_multicast_loop_v4`]: method@Self::set_multicast_loop_v4
1901    pub fn multicast_loop_v4(&self) -> io::Result<bool> {
1902        self.io.multicast_loop_v4()
1903    }
1904
1905    /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
1906    ///
1907    /// If enabled, multicast packets will be looped back to the local socket.
1908    ///
1909    /// # Note
1910    ///
1911    /// This may not have any affect on IPv6 sockets.
1912    pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> {
1913        self.io.set_multicast_loop_v4(on)
1914    }
1915
1916    /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
1917    ///
1918    /// For more information about this option, see [`set_multicast_ttl_v4`].
1919    ///
1920    /// [`set_multicast_ttl_v4`]: method@Self::set_multicast_ttl_v4
1921    pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
1922        self.io.multicast_ttl_v4()
1923    }
1924
1925    /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
1926    ///
1927    /// Indicates the time-to-live value of outgoing multicast packets for
1928    /// this socket. The default value is 1 which means that multicast packets
1929    /// don't leave the local network unless explicitly requested.
1930    ///
1931    /// # Note
1932    ///
1933    /// This may not have any affect on IPv6 sockets.
1934    pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> {
1935        self.io.set_multicast_ttl_v4(ttl)
1936    }
1937
1938    /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1939    ///
1940    /// For more information about this option, see [`set_multicast_loop_v6`].
1941    ///
1942    /// [`set_multicast_loop_v6`]: method@Self::set_multicast_loop_v6
1943    pub fn multicast_loop_v6(&self) -> io::Result<bool> {
1944        self.io.multicast_loop_v6()
1945    }
1946
1947    /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1948    ///
1949    /// Controls whether this socket sees the multicast packets it sends itself.
1950    ///
1951    /// # Note
1952    ///
1953    /// This may not have any affect on IPv4 sockets.
1954    pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> {
1955        self.io.set_multicast_loop_v6(on)
1956    }
1957
1958    /// Gets the value of the `IP_TTL` option for this socket.
1959    ///
1960    /// For more information about this option, see [`set_ttl`].
1961    ///
1962    /// [`set_ttl`]: method@Self::set_ttl
1963    ///
1964    /// # Examples
1965    ///
1966    /// ```no_run
1967    /// use tokio::net::UdpSocket;
1968    /// # use std::io;
1969    ///
1970    /// # async fn dox() -> io::Result<()> {
1971    /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
1972    ///
1973    /// println!("{:?}", sock.ttl()?);
1974    /// # Ok(())
1975    /// # }
1976    /// ```
1977    pub fn ttl(&self) -> io::Result<u32> {
1978        self.io.ttl()
1979    }
1980
1981    /// Sets the value for the `IP_TTL` option on this socket.
1982    ///
1983    /// This value sets the time-to-live field that is used in every packet sent
1984    /// from this socket.
1985    ///
1986    /// # Examples
1987    ///
1988    /// ```no_run
1989    /// use tokio::net::UdpSocket;
1990    /// # use std::io;
1991    ///
1992    /// # async fn dox() -> io::Result<()> {
1993    /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
1994    /// sock.set_ttl(60)?;
1995    ///
1996    /// # Ok(())
1997    /// # }
1998    /// ```
1999    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
2000        self.io.set_ttl(ttl)
2001    }
2002
2003    /// Gets the value of the `IP_TOS` option for this socket.
2004    ///
2005    /// For more information about this option, see [`set_tos`].
2006    ///
2007    /// **NOTE:** On Windows, `IP_TOS` is only supported on [Windows 8+ or
2008    /// Windows Server 2012+.](https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options)
2009    ///
2010    /// [`set_tos`]: Self::set_tos
2011    // https://docs.rs/socket2/0.5.3/src/socket2/socket.rs.html#1464
2012    #[cfg(not(any(
2013        target_os = "fuchsia",
2014        target_os = "redox",
2015        target_os = "solaris",
2016        target_os = "illumos",
2017        target_os = "haiku"
2018    )))]
2019    #[cfg_attr(
2020        docsrs,
2021        doc(cfg(not(any(
2022            target_os = "fuchsia",
2023            target_os = "redox",
2024            target_os = "solaris",
2025            target_os = "illumos",
2026            target_os = "haiku"
2027        ))))
2028    )]
2029    pub fn tos(&self) -> io::Result<u32> {
2030        self.as_socket().tos_v4()
2031    }
2032
2033    /// Sets the value for the `IP_TOS` option on this socket.
2034    ///
2035    /// This value sets the type-of-service field that is used in every packet
2036    /// sent from this socket.
2037    ///
2038    /// **NOTE:** On Windows, `IP_TOS` is only supported on [Windows 8+ or
2039    /// Windows Server 2012+.](https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options)
2040    // https://docs.rs/socket2/0.5.3/src/socket2/socket.rs.html#1446
2041    #[cfg(not(any(
2042        target_os = "fuchsia",
2043        target_os = "redox",
2044        target_os = "solaris",
2045        target_os = "illumos",
2046        target_os = "haiku"
2047    )))]
2048    #[cfg_attr(
2049        docsrs,
2050        doc(cfg(not(any(
2051            target_os = "fuchsia",
2052            target_os = "redox",
2053            target_os = "solaris",
2054            target_os = "illumos",
2055            target_os = "haiku"
2056        ))))
2057    )]
2058    pub fn set_tos(&self, tos: u32) -> io::Result<()> {
2059        self.as_socket().set_tos_v4(tos)
2060    }
2061
2062    /// Gets the value for the `SO_BINDTODEVICE` option on this socket
2063    ///
2064    /// This value gets the socket-bound device's interface name.
2065    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux",))]
2066    #[cfg_attr(
2067        docsrs,
2068        doc(cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux",)))
2069    )]
2070    pub fn device(&self) -> io::Result<Option<Vec<u8>>> {
2071        self.as_socket().device()
2072    }
2073
2074    /// Sets the value for the `SO_BINDTODEVICE` option on this socket
2075    ///
2076    /// If a socket is bound to an interface, only packets received from that
2077    /// particular interface are processed by the socket. Note that this only
2078    /// works for some socket types, particularly `AF_INET` sockets.
2079    ///
2080    /// If `interface` is `None` or an empty string it removes the binding.
2081    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
2082    #[cfg_attr(
2083        docsrs,
2084        doc(cfg(all(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))))
2085    )]
2086    pub fn bind_device(&self, interface: Option<&[u8]>) -> io::Result<()> {
2087        self.as_socket().bind_device(interface)
2088    }
2089
2090    /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
2091    ///
2092    /// This function specifies a new multicast group for this socket to join.
2093    /// The address must be a valid multicast address, and `interface` is the
2094    /// address of the local interface with which the system should join the
2095    /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
2096    /// interface is chosen by the system.
2097    pub fn join_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
2098        self.io.join_multicast_v4(&multiaddr, &interface)
2099    }
2100
2101    /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
2102    ///
2103    /// This function specifies a new multicast group for this socket to join.
2104    /// The address must be a valid multicast address, and `interface` is the
2105    /// index of the interface to join/leave (or 0 to indicate any interface).
2106    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
2107        self.io.join_multicast_v6(multiaddr, interface)
2108    }
2109
2110    /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
2111    ///
2112    /// For more information about this option, see [`join_multicast_v4`].
2113    ///
2114    /// [`join_multicast_v4`]: method@Self::join_multicast_v4
2115    pub fn leave_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
2116        self.io.leave_multicast_v4(&multiaddr, &interface)
2117    }
2118
2119    /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
2120    ///
2121    /// For more information about this option, see [`join_multicast_v6`].
2122    ///
2123    /// [`join_multicast_v6`]: method@Self::join_multicast_v6
2124    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
2125        self.io.leave_multicast_v6(multiaddr, interface)
2126    }
2127
2128    /// Returns the value of the `SO_ERROR` option.
2129    ///
2130    /// # Examples
2131    /// ```
2132    /// use tokio::net::UdpSocket;
2133    /// use std::io;
2134    ///
2135    /// #[tokio::main]
2136    /// async fn main() -> io::Result<()> {
2137    /// #   if cfg!(miri) { return Ok(()); } // No `socket` in miri.
2138    ///     // Create a socket
2139    ///     let socket = UdpSocket::bind("0.0.0.0:8080").await?;
2140    ///
2141    ///     if let Ok(Some(err)) = socket.take_error() {
2142    ///         println!("Got error: {:?}", err);
2143    ///     }
2144    ///
2145    ///     Ok(())
2146    /// }
2147    /// ```
2148    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
2149        self.io.take_error()
2150    }
2151}
2152
2153impl TryFrom<std::net::UdpSocket> for UdpSocket {
2154    type Error = io::Error;
2155
2156    /// Consumes stream, returning the tokio I/O object.
2157    ///
2158    /// This is equivalent to
2159    /// [`UdpSocket::from_std(stream)`](UdpSocket::from_std).
2160    fn try_from(stream: std::net::UdpSocket) -> Result<Self, Self::Error> {
2161        Self::from_std(stream)
2162    }
2163}
2164
2165impl fmt::Debug for UdpSocket {
2166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2167        self.io.fmt(f)
2168    }
2169}
2170
2171#[cfg(unix)]
2172mod sys {
2173    use super::UdpSocket;
2174    use std::os::unix::prelude::*;
2175
2176    impl AsRawFd for UdpSocket {
2177        fn as_raw_fd(&self) -> RawFd {
2178            self.io.as_raw_fd()
2179        }
2180    }
2181
2182    impl AsFd for UdpSocket {
2183        fn as_fd(&self) -> BorrowedFd<'_> {
2184            unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
2185        }
2186    }
2187}
2188
2189cfg_windows! {
2190    use crate::os::windows::io::{AsRawSocket, RawSocket};
2191    use crate::os::windows::io::{AsSocket, BorrowedSocket};
2192
2193    impl AsRawSocket for UdpSocket {
2194        fn as_raw_socket(&self) -> RawSocket {
2195            self.io.as_raw_socket()
2196        }
2197    }
2198
2199    impl AsSocket for UdpSocket {
2200        fn as_socket(&self) -> BorrowedSocket<'_> {
2201            unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
2202        }
2203    }
2204}