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