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(not(windows))]
258 {
259 use std::os::fd::{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 | Interest::ERROR, || 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
990 .registration()
991 .async_io(Interest::READABLE | Interest::ERROR, || {
992 let dst = buf.chunk_mut();
993 let dst =
994 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
995
996 let n = (*self.io).recv(dst)?;
997
998 // Safety: We trust `UdpSocket::recv` to have filled up `n` bytes in the
999 // buffer.
1000 unsafe {
1001 buf.advance_mut(n);
1002 }
1003
1004 Ok(n)
1005 })
1006 .await
1007 }
1008
1009 /// Tries to receive a single datagram message on the socket. On success,
1010 /// returns the number of bytes read and the origin.
1011 ///
1012 /// This method must be called with valid byte array `buf` of sufficient size
1013 /// to hold the message bytes. If a message is too long to fit in the
1014 /// supplied buffer, excess bytes may be discarded.
1015 ///
1016 /// This method can be used even if `buf` is uninitialized.
1017 ///
1018 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1019 /// returned. This function is usually paired with `readable()`.
1020 ///
1021 /// # Notes
1022 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1023 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1024 /// Because UDP is stateless and does not validate the origin of a packet,
1025 /// the attacker does not need to be able to intercept traffic in order to interfere.
1026 /// It is important to be aware of this when designing your application-level protocol.
1027 ///
1028 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1029 ///
1030 /// # Examples
1031 ///
1032 /// ```no_run
1033 /// use tokio::net::UdpSocket;
1034 /// use std::io;
1035 ///
1036 /// #[tokio::main]
1037 /// async fn main() -> io::Result<()> {
1038 /// // Connect to a peer
1039 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1040 ///
1041 /// loop {
1042 /// // Wait for the socket to be readable
1043 /// socket.readable().await?;
1044 ///
1045 /// let mut buf = Vec::with_capacity(1024);
1046 ///
1047 /// // Try to recv data, this may still fail with `WouldBlock`
1048 /// // if the readiness event is a false positive.
1049 /// match socket.try_recv_buf_from(&mut buf) {
1050 /// Ok((n, _addr)) => {
1051 /// println!("GOT {:?}", &buf[..n]);
1052 /// break;
1053 /// }
1054 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1055 /// continue;
1056 /// }
1057 /// Err(e) => {
1058 /// return Err(e);
1059 /// }
1060 /// }
1061 /// }
1062 ///
1063 /// Ok(())
1064 /// }
1065 /// ```
1066 pub fn try_recv_buf_from<B: BufMut>(&self, buf: &mut B) -> io::Result<(usize, SocketAddr)> {
1067 self.io.registration().try_io(Interest::READABLE, || {
1068 let dst = buf.chunk_mut();
1069 let dst =
1070 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
1071
1072 let (n, addr) = (*self.io).recv_from(dst)?;
1073
1074 // Safety: We trust `UdpSocket::recv_from` to have filled up `n` bytes in the
1075 // buffer.
1076 unsafe {
1077 buf.advance_mut(n);
1078 }
1079
1080 Ok((n, addr))
1081 })
1082 }
1083
1084 /// Receives a single datagram message on the socket, advancing the
1085 /// buffer's internal cursor, returning how many bytes were read and the origin.
1086 ///
1087 /// This method must be called with valid byte array `buf` of sufficient size
1088 /// to hold the message bytes. If a message is too long to fit in the
1089 /// supplied buffer, excess bytes may be discarded.
1090 ///
1091 /// This method can be used even if `buf` is uninitialized.
1092 ///
1093 /// # Notes
1094 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1095 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1096 /// Because UDP is stateless and does not validate the origin of a packet,
1097 /// the attacker does not need to be able to intercept traffic in order to interfere.
1098 /// It is important to be aware of this when designing your application-level protocol.
1099 ///
1100 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1101 ///
1102 /// # Examples
1103 ///
1104 /// ```no_run
1105 /// use tokio::net::UdpSocket;
1106 /// use std::io;
1107 ///
1108 /// #[tokio::main]
1109 /// async fn main() -> io::Result<()> {
1110 /// // Connect to a peer
1111 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1112 /// socket.connect("127.0.0.1:8081").await?;
1113 ///
1114 /// let mut buf = Vec::with_capacity(512);
1115 /// let (len, addr) = socket.recv_buf_from(&mut buf).await?;
1116 ///
1117 /// println!("received {:?} bytes from {:?}", len, addr);
1118 ///
1119 /// Ok(())
1120 /// }
1121 /// ```
1122 pub async fn recv_buf_from<B: BufMut>(&self, buf: &mut B) -> io::Result<(usize, SocketAddr)> {
1123 self.io
1124 .registration()
1125 .async_io(Interest::READABLE | Interest::ERROR, || {
1126 let dst = buf.chunk_mut();
1127 let dst =
1128 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
1129
1130 let (n, addr) = (*self.io).recv_from(dst)?;
1131
1132 // Safety: We trust `UdpSocket::recv_from` to have filled up `n` bytes in the
1133 // buffer.
1134 unsafe {
1135 buf.advance_mut(n);
1136 }
1137
1138 Ok((n, addr))
1139 })
1140 .await
1141 }
1142 }
1143
1144 /// Sends data on the socket to the given address. On success, returns the
1145 /// number of bytes written.
1146 ///
1147 /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
1148 /// documentation for concrete examples.
1149 ///
1150 /// It is possible for `addr` to yield multiple addresses, but `send_to`
1151 /// will only send data to the first address yielded by `addr`.
1152 ///
1153 /// This will return an error when the IP version of the local socket does
1154 /// not match that returned from [`ToSocketAddrs`].
1155 ///
1156 /// [`ToSocketAddrs`]: crate::net::ToSocketAddrs
1157 ///
1158 /// # Cancel safety
1159 ///
1160 /// This method is cancel safe. If `send_to` is used as the event in a
1161 /// [`tokio::select!`](crate::select) statement and some other branch
1162 /// completes first, then it is guaranteed that the message was not sent.
1163 ///
1164 /// # Example
1165 ///
1166 /// ```no_run
1167 /// use tokio::net::UdpSocket;
1168 /// use std::io;
1169 ///
1170 /// #[tokio::main]
1171 /// async fn main() -> io::Result<()> {
1172 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1173 /// let len = socket.send_to(b"hello world", "127.0.0.1:8081").await?;
1174 ///
1175 /// println!("Sent {} bytes", len);
1176 ///
1177 /// Ok(())
1178 /// }
1179 /// ```
1180 pub async fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
1181 let mut addrs = to_socket_addrs(addr).await?;
1182
1183 match addrs.next() {
1184 Some(target) => self.send_to_addr(buf, target).await,
1185 None => Err(io::Error::new(
1186 io::ErrorKind::InvalidInput,
1187 "no addresses to send data to",
1188 )),
1189 }
1190 }
1191
1192 /// Attempts to send data on the socket to a given address.
1193 ///
1194 /// Note that on multiple calls to a `poll_*` method in the send direction, only the
1195 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1196 /// receive a wakeup.
1197 ///
1198 /// # Return value
1199 ///
1200 /// The function returns:
1201 ///
1202 /// * `Poll::Pending` if the socket is not ready to write
1203 /// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent.
1204 /// * `Poll::Ready(Err(e))` if an error is encountered.
1205 ///
1206 /// # Errors
1207 ///
1208 /// This function may encounter any standard I/O error except `WouldBlock`.
1209 pub fn poll_send_to(
1210 &self,
1211 cx: &mut Context<'_>,
1212 buf: &[u8],
1213 target: SocketAddr,
1214 ) -> Poll<io::Result<usize>> {
1215 self.io
1216 .registration()
1217 .poll_write_io(cx, || self.io.send_to(buf, target))
1218 }
1219
1220 /// Tries to send data on the socket to the given address, but if the send is
1221 /// blocked this will return right away.
1222 ///
1223 /// This function is usually paired with `writable()`.
1224 ///
1225 /// # Returns
1226 ///
1227 /// If successful, returns the number of bytes sent
1228 ///
1229 /// Users should ensure that when the remote cannot receive, the
1230 /// [`ErrorKind::WouldBlock`] is properly handled. An error can also occur
1231 /// if the IP version of the socket does not match that of `target`.
1232 ///
1233 /// [`ErrorKind::WouldBlock`]: std::io::ErrorKind::WouldBlock
1234 ///
1235 /// # Example
1236 ///
1237 /// ```no_run
1238 /// use tokio::net::UdpSocket;
1239 /// use std::error::Error;
1240 /// use std::io;
1241 ///
1242 /// #[tokio::main]
1243 /// async fn main() -> Result<(), Box<dyn Error>> {
1244 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1245 ///
1246 /// let dst = "127.0.0.1:8081".parse()?;
1247 ///
1248 /// loop {
1249 /// socket.writable().await?;
1250 ///
1251 /// match socket.try_send_to(&b"hello world"[..], dst) {
1252 /// Ok(sent) => {
1253 /// println!("sent {} bytes", sent);
1254 /// break;
1255 /// }
1256 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1257 /// // Writable false positive.
1258 /// continue;
1259 /// }
1260 /// Err(e) => return Err(e.into()),
1261 /// }
1262 /// }
1263 ///
1264 /// Ok(())
1265 /// }
1266 /// ```
1267 pub fn try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
1268 self.io
1269 .registration()
1270 .try_io(Interest::WRITABLE, || self.io.send_to(buf, target))
1271 }
1272
1273 async fn send_to_addr(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
1274 self.io
1275 .registration()
1276 .async_io(Interest::WRITABLE, || self.io.send_to(buf, target))
1277 .await
1278 }
1279
1280 /// Receives a single datagram message on the socket. On success, returns
1281 /// the number of bytes read and the origin.
1282 ///
1283 /// The function must be called with valid byte array `buf` of sufficient
1284 /// size to hold the message bytes. If a message is too long to fit in the
1285 /// supplied buffer, excess bytes may be discarded.
1286 ///
1287 /// # Cancel safety
1288 ///
1289 /// This method is cancel safe. If `recv_from` is used as the event in a
1290 /// [`tokio::select!`](crate::select) statement and some other branch
1291 /// completes first, it is guaranteed that no messages were received on this
1292 /// socket.
1293 ///
1294 /// # Example
1295 ///
1296 /// ```no_run
1297 /// use tokio::net::UdpSocket;
1298 /// use std::io;
1299 ///
1300 /// #[tokio::main]
1301 /// async fn main() -> io::Result<()> {
1302 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1303 ///
1304 /// let mut buf = vec![0u8; 32];
1305 /// let (len, addr) = socket.recv_from(&mut buf).await?;
1306 ///
1307 /// println!("received {:?} bytes from {:?}", len, addr);
1308 ///
1309 /// Ok(())
1310 /// }
1311 /// ```
1312 ///
1313 /// # Notes
1314 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1315 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1316 /// Because UDP is stateless and does not validate the origin of a packet,
1317 /// the attacker does not need to be able to intercept traffic in order to interfere.
1318 /// It is important to be aware of this when designing your application-level protocol.
1319 ///
1320 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1321 pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1322 self.io
1323 .registration()
1324 .async_io(Interest::READABLE | Interest::ERROR, || {
1325 self.io.recv_from(buf)
1326 })
1327 .await
1328 }
1329
1330 /// Attempts to receive a single datagram on the socket.
1331 ///
1332 /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1333 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1334 /// receive a wakeup.
1335 ///
1336 /// # Return value
1337 ///
1338 /// The function returns:
1339 ///
1340 /// * `Poll::Pending` if the socket is not ready to read
1341 /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1342 /// * `Poll::Ready(Err(e))` if an error is encountered.
1343 ///
1344 /// # Errors
1345 ///
1346 /// This function may encounter any standard I/O error except `WouldBlock`.
1347 ///
1348 /// # Notes
1349 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1350 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1351 /// Because UDP is stateless and does not validate the origin of a packet,
1352 /// the attacker does not need to be able to intercept traffic in order to interfere.
1353 /// It is important to be aware of this when designing your application-level protocol.
1354 ///
1355 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1356 pub fn poll_recv_from(
1357 &self,
1358 cx: &mut Context<'_>,
1359 buf: &mut ReadBuf<'_>,
1360 ) -> Poll<io::Result<SocketAddr>> {
1361 #[allow(clippy::blocks_in_conditions)]
1362 let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1363 // Safety: will not read the maybe uninitialized bytes.
1364 let b = unsafe {
1365 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1366 };
1367
1368 self.io.recv_from(b)
1369 }))?;
1370
1371 // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1372 unsafe {
1373 buf.assume_init(n);
1374 }
1375 buf.advance(n);
1376 Poll::Ready(Ok(addr))
1377 }
1378
1379 /// Tries to receive a single datagram message on the socket. On success,
1380 /// returns the number of bytes read and the origin.
1381 ///
1382 /// This method must be called with valid byte array `buf` of sufficient size
1383 /// to hold the message bytes. If a message is too long to fit in the
1384 /// supplied buffer, excess bytes may be discarded.
1385 ///
1386 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1387 /// returned. This function is usually paired with `readable()`.
1388 ///
1389 /// # Notes
1390 ///
1391 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1392 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1393 /// Because UDP is stateless and does not validate the origin of a packet,
1394 /// the attacker does not need to be able to intercept traffic in order to interfere.
1395 /// It is important to be aware of this when designing your application-level protocol.
1396 ///
1397 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1398 ///
1399 /// # Examples
1400 ///
1401 /// ```no_run
1402 /// use tokio::net::UdpSocket;
1403 /// use std::io;
1404 ///
1405 /// #[tokio::main]
1406 /// async fn main() -> io::Result<()> {
1407 /// // Connect to a peer
1408 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1409 ///
1410 /// loop {
1411 /// // Wait for the socket to be readable
1412 /// socket.readable().await?;
1413 ///
1414 /// // The buffer is **not** included in the async task and will
1415 /// // only exist on the stack.
1416 /// let mut buf = [0; 1024];
1417 ///
1418 /// // Try to recv data, this may still fail with `WouldBlock`
1419 /// // if the readiness event is a false positive.
1420 /// match socket.try_recv_from(&mut buf) {
1421 /// Ok((n, _addr)) => {
1422 /// println!("GOT {:?}", &buf[..n]);
1423 /// break;
1424 /// }
1425 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1426 /// continue;
1427 /// }
1428 /// Err(e) => {
1429 /// return Err(e);
1430 /// }
1431 /// }
1432 /// }
1433 ///
1434 /// Ok(())
1435 /// }
1436 /// ```
1437 pub fn try_recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1438 self.io
1439 .registration()
1440 .try_io(Interest::READABLE, || self.io.recv_from(buf))
1441 }
1442
1443 /// Tries to read or write from the socket using a user-provided IO operation.
1444 ///
1445 /// If the socket is ready, the provided closure is called. The closure
1446 /// should attempt to perform IO operation on the socket by manually
1447 /// calling the appropriate syscall. If the operation fails because the
1448 /// socket is not actually ready, then the closure should return a
1449 /// `WouldBlock` error and the readiness flag is cleared. The return value
1450 /// of the closure is then returned by `try_io`.
1451 ///
1452 /// If the socket is not ready, then the closure is not called
1453 /// and a `WouldBlock` error is returned.
1454 ///
1455 /// The closure should only return a `WouldBlock` error if it has performed
1456 /// an IO operation on the socket that failed due to the socket not being
1457 /// ready. Returning a `WouldBlock` error in any other situation will
1458 /// incorrectly clear the readiness flag, which can cause the socket to
1459 /// behave incorrectly.
1460 ///
1461 /// The closure should not perform the IO operation using any of the methods
1462 /// defined on the Tokio `UdpSocket` type, as this will mess with the
1463 /// readiness flag and can cause the socket to behave incorrectly.
1464 ///
1465 /// This method is not intended to be used with combined interests.
1466 /// The closure should perform only one type of IO operation, so it should not
1467 /// require more than one ready state. This method may panic or sleep forever
1468 /// if it is called with a combined interest.
1469 ///
1470 /// Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.
1471 ///
1472 /// [`readable()`]: UdpSocket::readable()
1473 /// [`writable()`]: UdpSocket::writable()
1474 /// [`ready()`]: UdpSocket::ready()
1475 pub fn try_io<R>(
1476 &self,
1477 interest: Interest,
1478 f: impl FnOnce() -> io::Result<R>,
1479 ) -> io::Result<R> {
1480 self.io
1481 .registration()
1482 .try_io(interest, || self.io.try_io(f))
1483 }
1484
1485 /// Reads or writes from the socket using a user-provided IO operation.
1486 ///
1487 /// The readiness of the socket is awaited and when the socket is ready,
1488 /// the provided closure is called. The closure should attempt to perform
1489 /// IO operation on the socket by manually calling the appropriate syscall.
1490 /// If the operation fails because the socket is not actually ready,
1491 /// then the closure should return a `WouldBlock` error. In such case the
1492 /// readiness flag is cleared and the socket readiness is awaited again.
1493 /// This loop is repeated until the closure returns an `Ok` or an error
1494 /// other than `WouldBlock`.
1495 ///
1496 /// The closure should only return a `WouldBlock` error if it has performed
1497 /// an IO operation on the socket that failed due to the socket not being
1498 /// ready. Returning a `WouldBlock` error in any other situation will
1499 /// incorrectly clear the readiness flag, which can cause the socket to
1500 /// behave incorrectly.
1501 ///
1502 /// The closure should not perform the IO operation using any of the methods
1503 /// defined on the Tokio `UdpSocket` type, as this will mess with the
1504 /// readiness flag and can cause the socket to behave incorrectly.
1505 ///
1506 /// This method is not intended to be used with combined interests.
1507 /// The closure should perform only one type of IO operation, so it should not
1508 /// require more than one ready state. This method may panic or sleep forever
1509 /// if it is called with a combined interest.
1510 pub async fn async_io<R>(
1511 &self,
1512 interest: Interest,
1513 mut f: impl FnMut() -> io::Result<R>,
1514 ) -> io::Result<R> {
1515 self.io
1516 .registration()
1517 .async_io(interest, || self.io.try_io(&mut f))
1518 .await
1519 }
1520
1521 /// Receives a single datagram from the connected address without removing it from the queue.
1522 /// On success, returns the number of bytes read from whence the data came.
1523 ///
1524 /// # Notes
1525 ///
1526 /// On Windows, if the data is larger than the buffer specified, the buffer
1527 /// is filled with the first part of the data, and peek returns the error
1528 /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1529 /// Make sure to always use a sufficiently large buffer to hold the
1530 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1531 ///
1532 /// MacOS will return an error if you pass a zero-sized buffer.
1533 ///
1534 /// If you're merely interested in learning the sender of the data at the head of the queue,
1535 /// try [`peek_sender`].
1536 ///
1537 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1538 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1539 /// Because UDP is stateless and does not validate the origin of a packet,
1540 /// the attacker does not need to be able to intercept traffic in order to interfere.
1541 /// It is important to be aware of this when designing your application-level protocol.
1542 ///
1543 /// # Examples
1544 ///
1545 /// ```no_run
1546 /// use tokio::net::UdpSocket;
1547 /// use std::io;
1548 ///
1549 /// #[tokio::main]
1550 /// async fn main() -> io::Result<()> {
1551 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1552 ///
1553 /// let mut buf = vec![0u8; 32];
1554 /// let len = socket.peek(&mut buf).await?;
1555 ///
1556 /// println!("peeked {:?} bytes", len);
1557 ///
1558 /// Ok(())
1559 /// }
1560 /// ```
1561 ///
1562 /// [`peek_sender`]: method@Self::peek_sender
1563 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1564 pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1565 self.io
1566 .registration()
1567 .async_io(Interest::READABLE | Interest::ERROR, || self.io.peek(buf))
1568 .await
1569 }
1570
1571 /// Receives data from the connected address, without removing it from the input queue.
1572 ///
1573 /// # Notes
1574 ///
1575 /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1576 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1577 /// receive a wakeup
1578 ///
1579 /// On Windows, if the data is larger than the buffer specified, the buffer
1580 /// is filled with the first part of the data, and peek returns the error
1581 /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1582 /// Make sure to always use a sufficiently large buffer to hold the
1583 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1584 ///
1585 /// MacOS will return an error if you pass a zero-sized buffer.
1586 ///
1587 /// If you're merely interested in learning the sender of the data at the head of the queue,
1588 /// try [`poll_peek_sender`].
1589 ///
1590 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1591 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1592 /// Because UDP is stateless and does not validate the origin of a packet,
1593 /// the attacker does not need to be able to intercept traffic in order to interfere.
1594 /// It is important to be aware of this when designing your application-level protocol.
1595 ///
1596 /// # Return value
1597 ///
1598 /// The function returns:
1599 ///
1600 /// * `Poll::Pending` if the socket is not ready to read
1601 /// * `Poll::Ready(Ok(()))` reads data into `ReadBuf` if the socket is ready
1602 /// * `Poll::Ready(Err(e))` if an error is encountered.
1603 ///
1604 /// # Errors
1605 ///
1606 /// This function may encounter any standard I/O error except `WouldBlock`.
1607 ///
1608 /// [`poll_peek_sender`]: method@Self::poll_peek_sender
1609 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1610 pub fn poll_peek(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
1611 #[allow(clippy::blocks_in_conditions)]
1612 let n = ready!(self.io.registration().poll_read_io(cx, || {
1613 // Safety: will not read the maybe uninitialized bytes.
1614 let b = unsafe {
1615 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1616 };
1617
1618 self.io.peek(b)
1619 }))?;
1620
1621 // Safety: We trust `peek` to have filled up `n` bytes in the buffer.
1622 unsafe {
1623 buf.assume_init(n);
1624 }
1625 buf.advance(n);
1626 Poll::Ready(Ok(()))
1627 }
1628
1629 /// Tries to receive data on the connected address without removing it from the input queue.
1630 /// On success, returns the number of bytes read.
1631 ///
1632 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1633 /// returned. This function is usually paired with `readable()`.
1634 ///
1635 /// # Notes
1636 ///
1637 /// On Windows, if the data is larger than the buffer specified, the buffer
1638 /// is filled with the first part of the data, and peek returns the error
1639 /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1640 /// Make sure to always use a sufficiently large buffer to hold the
1641 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1642 ///
1643 /// MacOS will return an error if you pass a zero-sized buffer.
1644 ///
1645 /// If you're merely interested in learning the sender of the data at the head of the queue,
1646 /// try [`try_peek_sender`].
1647 ///
1648 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1649 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1650 /// Because UDP is stateless and does not validate the origin of a packet,
1651 /// the attacker does not need to be able to intercept traffic in order to interfere.
1652 /// It is important to be aware of this when designing your application-level protocol.
1653 ///
1654 /// [`try_peek_sender`]: method@Self::try_peek_sender
1655 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1656 pub fn try_peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1657 self.io
1658 .registration()
1659 .try_io(Interest::READABLE, || self.io.peek(buf))
1660 }
1661
1662 /// Receives data from the socket, without removing it from the input queue.
1663 /// On success, returns the number of bytes read and the address from whence
1664 /// the data came.
1665 ///
1666 /// # Notes
1667 ///
1668 /// On Windows, if the data is larger than the buffer specified, the buffer
1669 /// is filled with the first part of the data, and `peek_from` returns the error
1670 /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1671 /// Make sure to always use a sufficiently large buffer to hold the
1672 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1673 ///
1674 /// MacOS will return an error if you pass a zero-sized buffer.
1675 ///
1676 /// If you're merely interested in learning the sender of the data at the head of the queue,
1677 /// try [`peek_sender`].
1678 ///
1679 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1680 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1681 /// Because UDP is stateless and does not validate the origin of a packet,
1682 /// the attacker does not need to be able to intercept traffic in order to interfere.
1683 /// It is important to be aware of this when designing your application-level protocol.
1684 ///
1685 /// # Examples
1686 ///
1687 /// ```no_run
1688 /// use tokio::net::UdpSocket;
1689 /// use std::io;
1690 ///
1691 /// #[tokio::main]
1692 /// async fn main() -> io::Result<()> {
1693 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1694 ///
1695 /// let mut buf = vec![0u8; 32];
1696 /// let (len, addr) = socket.peek_from(&mut buf).await?;
1697 ///
1698 /// println!("peeked {:?} bytes from {:?}", len, addr);
1699 ///
1700 /// Ok(())
1701 /// }
1702 /// ```
1703 ///
1704 /// [`peek_sender`]: method@Self::peek_sender
1705 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1706 pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1707 self.io
1708 .registration()
1709 .async_io(Interest::READABLE | Interest::ERROR, || {
1710 self.io.peek_from(buf)
1711 })
1712 .await
1713 }
1714
1715 /// Receives data from the socket, without removing it from the input queue.
1716 /// On success, returns the sending address of the datagram.
1717 ///
1718 /// # Notes
1719 ///
1720 /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1721 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1722 /// receive a wakeup
1723 ///
1724 /// On Windows, if the data is larger than the buffer specified, the buffer
1725 /// is filled with the first part of the data, and peek returns the error
1726 /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1727 /// Make sure to always use a sufficiently large buffer to hold the
1728 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1729 ///
1730 /// MacOS will return an error if you pass a zero-sized buffer.
1731 ///
1732 /// If you're merely interested in learning the sender of the data at the head of the queue,
1733 /// try [`poll_peek_sender`].
1734 ///
1735 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1736 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1737 /// Because UDP is stateless and does not validate the origin of a packet,
1738 /// the attacker does not need to be able to intercept traffic in order to interfere.
1739 /// It is important to be aware of this when designing your application-level protocol.
1740 ///
1741 /// # Return value
1742 ///
1743 /// The function returns:
1744 ///
1745 /// * `Poll::Pending` if the socket is not ready to read
1746 /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1747 /// * `Poll::Ready(Err(e))` if an error is encountered.
1748 ///
1749 /// # Errors
1750 ///
1751 /// This function may encounter any standard I/O error except `WouldBlock`.
1752 ///
1753 /// [`poll_peek_sender`]: method@Self::poll_peek_sender
1754 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1755 pub fn poll_peek_from(
1756 &self,
1757 cx: &mut Context<'_>,
1758 buf: &mut ReadBuf<'_>,
1759 ) -> Poll<io::Result<SocketAddr>> {
1760 #[allow(clippy::blocks_in_conditions)]
1761 let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1762 // Safety: will not read the maybe uninitialized bytes.
1763 let b = unsafe {
1764 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1765 };
1766
1767 self.io.peek_from(b)
1768 }))?;
1769
1770 // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1771 unsafe {
1772 buf.assume_init(n);
1773 }
1774 buf.advance(n);
1775 Poll::Ready(Ok(addr))
1776 }
1777
1778 /// Tries to receive data on the socket without removing it from the input queue.
1779 /// On success, returns the number of bytes read and the sending address of the
1780 /// datagram.
1781 ///
1782 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1783 /// returned. This function is usually paired with `readable()`.
1784 ///
1785 /// # Notes
1786 ///
1787 /// On Windows, if the data is larger than the buffer specified, the buffer
1788 /// is filled with the first part of the data, and peek returns the error
1789 /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1790 /// Make sure to always use a sufficiently large buffer to hold the
1791 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1792 ///
1793 /// MacOS will return an error if you pass a zero-sized buffer.
1794 ///
1795 /// If you're merely interested in learning the sender of the data at the head of the queue,
1796 /// try [`try_peek_sender`].
1797 ///
1798 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1799 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1800 /// Because UDP is stateless and does not validate the origin of a packet,
1801 /// the attacker does not need to be able to intercept traffic in order to interfere.
1802 /// It is important to be aware of this when designing your application-level protocol.
1803 ///
1804 /// [`try_peek_sender`]: method@Self::try_peek_sender
1805 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1806 pub fn try_peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1807 self.io
1808 .registration()
1809 .try_io(Interest::READABLE, || self.io.peek_from(buf))
1810 }
1811
1812 /// Retrieve the sender of the data at the head of the input queue, waiting if empty.
1813 ///
1814 /// This is equivalent to calling [`peek_from`] with a zero-sized buffer,
1815 /// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
1816 ///
1817 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1818 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1819 /// Because UDP is stateless and does not validate the origin of a packet,
1820 /// the attacker does not need to be able to intercept traffic in order to interfere.
1821 /// It is important to be aware of this when designing your application-level protocol.
1822 ///
1823 /// [`peek_from`]: method@Self::peek_from
1824 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1825 pub async fn peek_sender(&self) -> io::Result<SocketAddr> {
1826 self.io
1827 .registration()
1828 .async_io(Interest::READABLE | Interest::ERROR, || {
1829 self.peek_sender_inner()
1830 })
1831 .await
1832 }
1833
1834 /// Retrieve the sender of the data at the head of the input queue,
1835 /// scheduling a wakeup if empty.
1836 ///
1837 /// This is equivalent to calling [`poll_peek_from`] with a zero-sized buffer,
1838 /// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
1839 ///
1840 /// # Notes
1841 ///
1842 /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1843 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1844 /// receive a wakeup.
1845 ///
1846 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1847 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1848 /// Because UDP is stateless and does not validate the origin of a packet,
1849 /// the attacker does not need to be able to intercept traffic in order to interfere.
1850 /// It is important to be aware of this when designing your application-level protocol.
1851 ///
1852 /// [`poll_peek_from`]: method@Self::poll_peek_from
1853 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1854 pub fn poll_peek_sender(&self, cx: &mut Context<'_>) -> Poll<io::Result<SocketAddr>> {
1855 self.io
1856 .registration()
1857 .poll_read_io(cx, || self.peek_sender_inner())
1858 }
1859
1860 /// Try to retrieve the sender of the data at the head of the input queue.
1861 ///
1862 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1863 /// returned. This function is usually paired with `readable()`.
1864 ///
1865 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1866 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1867 /// Because UDP is stateless and does not validate the origin of a packet,
1868 /// the attacker does not need to be able to intercept traffic in order to interfere.
1869 /// It is important to be aware of this when designing your application-level protocol.
1870 ///
1871 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1872 pub fn try_peek_sender(&self) -> io::Result<SocketAddr> {
1873 self.io
1874 .registration()
1875 .try_io(Interest::READABLE, || self.peek_sender_inner())
1876 }
1877
1878 #[inline]
1879 fn peek_sender_inner(&self) -> io::Result<SocketAddr> {
1880 self.io.try_io(|| {
1881 self.as_socket()
1882 .peek_sender()?
1883 // May be `None` if the platform doesn't populate the sender for some reason.
1884 // In testing, that only occurred on macOS if you pass a zero-sized buffer,
1885 // but the implementation of `Socket::peek_sender()` covers that.
1886 .as_socket()
1887 .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "sender not available"))
1888 })
1889 }
1890
1891 /// Gets the value of the `SO_BROADCAST` option for this socket.
1892 ///
1893 /// For more information about this option, see [`set_broadcast`].
1894 ///
1895 /// [`set_broadcast`]: method@Self::set_broadcast
1896 pub fn broadcast(&self) -> io::Result<bool> {
1897 self.io.broadcast()
1898 }
1899
1900 /// Sets the value of the `SO_BROADCAST` option for this socket.
1901 ///
1902 /// When enabled, this socket is allowed to send packets to a broadcast
1903 /// address.
1904 pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
1905 self.io.set_broadcast(on)
1906 }
1907
1908 /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
1909 ///
1910 /// For more information about this option, see [`set_multicast_loop_v4`].
1911 ///
1912 /// [`set_multicast_loop_v4`]: method@Self::set_multicast_loop_v4
1913 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
1914 self.io.multicast_loop_v4()
1915 }
1916
1917 /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
1918 ///
1919 /// If enabled, multicast packets will be looped back to the local socket.
1920 ///
1921 /// # Note
1922 ///
1923 /// This may not have any effect on IPv6 sockets.
1924 pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> {
1925 self.io.set_multicast_loop_v4(on)
1926 }
1927
1928 /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
1929 ///
1930 /// For more information about this option, see [`set_multicast_ttl_v4`].
1931 ///
1932 /// [`set_multicast_ttl_v4`]: method@Self::set_multicast_ttl_v4
1933 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
1934 self.io.multicast_ttl_v4()
1935 }
1936
1937 /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
1938 ///
1939 /// Indicates the time-to-live value of outgoing multicast packets for
1940 /// this socket. The default value is 1 which means that multicast packets
1941 /// don't leave the local network unless explicitly requested.
1942 ///
1943 /// # Note
1944 ///
1945 /// This may not have any effect on IPv6 sockets.
1946 pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> {
1947 self.io.set_multicast_ttl_v4(ttl)
1948 }
1949
1950 /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1951 ///
1952 /// For more information about this option, see [`set_multicast_loop_v6`].
1953 ///
1954 /// [`set_multicast_loop_v6`]: method@Self::set_multicast_loop_v6
1955 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
1956 self.io.multicast_loop_v6()
1957 }
1958
1959 /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1960 ///
1961 /// Controls whether this socket sees the multicast packets it sends itself.
1962 ///
1963 /// # Note
1964 ///
1965 /// This may not have any effect on IPv4 sockets.
1966 pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> {
1967 self.io.set_multicast_loop_v6(on)
1968 }
1969
1970 /// Gets the value of the `IPV6_TCLASS` option for this socket.
1971 ///
1972 /// For more information about this option, see [`set_tclass_v6`].
1973 ///
1974 /// [`set_tclass_v6`]: Self::set_tclass_v6
1975 // https://docs.rs/socket2/0.6.1/src/socket2/sys/unix.rs.html#2541
1976 #[cfg(any(
1977 target_os = "android",
1978 target_os = "dragonfly",
1979 target_os = "freebsd",
1980 target_os = "fuchsia",
1981 target_os = "linux",
1982 target_os = "macos",
1983 target_os = "netbsd",
1984 target_os = "openbsd",
1985 target_os = "cygwin",
1986 ))]
1987 #[cfg_attr(
1988 docsrs,
1989 doc(cfg(any(
1990 target_os = "android",
1991 target_os = "dragonfly",
1992 target_os = "freebsd",
1993 target_os = "fuchsia",
1994 target_os = "linux",
1995 target_os = "macos",
1996 target_os = "netbsd",
1997 target_os = "openbsd",
1998 target_os = "cygwin",
1999 )))
2000 )]
2001 pub fn tclass_v6(&self) -> io::Result<u32> {
2002 self.as_socket().tclass_v6()
2003 }
2004
2005 /// Sets the value for the `IPV6_TCLASS` option on this socket.
2006 ///
2007 /// Specifies the traffic class field that is used in every packet
2008 /// sent from this socket.
2009 ///
2010 /// # Note
2011 ///
2012 /// This may not have any effect on IPv4 sockets.
2013 // https://docs.rs/socket2/0.6.1/src/socket2/sys/unix.rs.html#2566
2014 #[cfg(any(
2015 target_os = "android",
2016 target_os = "dragonfly",
2017 target_os = "freebsd",
2018 target_os = "fuchsia",
2019 target_os = "linux",
2020 target_os = "macos",
2021 target_os = "netbsd",
2022 target_os = "openbsd",
2023 target_os = "cygwin",
2024 ))]
2025 #[cfg_attr(
2026 docsrs,
2027 doc(cfg(any(
2028 target_os = "android",
2029 target_os = "dragonfly",
2030 target_os = "freebsd",
2031 target_os = "fuchsia",
2032 target_os = "linux",
2033 target_os = "macos",
2034 target_os = "netbsd",
2035 target_os = "openbsd",
2036 target_os = "cygwin",
2037 )))
2038 )]
2039 pub fn set_tclass_v6(&self, tclass: u32) -> io::Result<()> {
2040 self.as_socket().set_tclass_v6(tclass)
2041 }
2042
2043 /// Gets the value of the `IP_TTL` option for this socket.
2044 ///
2045 /// For more information about this option, see [`set_ttl`].
2046 ///
2047 /// [`set_ttl`]: method@Self::set_ttl
2048 ///
2049 /// # Examples
2050 ///
2051 /// ```no_run
2052 /// use tokio::net::UdpSocket;
2053 /// # use std::io;
2054 ///
2055 /// # async fn dox() -> io::Result<()> {
2056 /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
2057 ///
2058 /// println!("{:?}", sock.ttl()?);
2059 /// # Ok(())
2060 /// # }
2061 /// ```
2062 pub fn ttl(&self) -> io::Result<u32> {
2063 self.io.ttl()
2064 }
2065
2066 /// Sets the value for the `IP_TTL` option on this socket.
2067 ///
2068 /// This value sets the time-to-live field that is used in every packet sent
2069 /// from this socket.
2070 ///
2071 /// # Examples
2072 ///
2073 /// ```no_run
2074 /// use tokio::net::UdpSocket;
2075 /// # use std::io;
2076 ///
2077 /// # async fn dox() -> io::Result<()> {
2078 /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
2079 /// sock.set_ttl(60)?;
2080 ///
2081 /// # Ok(())
2082 /// # }
2083 /// ```
2084 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
2085 self.io.set_ttl(ttl)
2086 }
2087
2088 /// Gets the value of the `IP_TOS` option for this socket.
2089 ///
2090 /// For more information about this option, see [`set_tos_v4`].
2091 ///
2092 /// [`set_tos_v4`]: Self::set_tos_v4
2093 // https://docs.rs/socket2/0.6.1/src/socket2/socket.rs.html#1585
2094 #[cfg(not(any(
2095 target_os = "fuchsia",
2096 target_os = "redox",
2097 target_os = "solaris",
2098 target_os = "illumos",
2099 target_os = "haiku",
2100 target_os = "wasi",
2101 )))]
2102 #[cfg_attr(
2103 docsrs,
2104 doc(cfg(not(any(
2105 target_os = "fuchsia",
2106 target_os = "redox",
2107 target_os = "solaris",
2108 target_os = "illumos",
2109 target_os = "haiku",
2110 target_os = "wasi",
2111 ))))
2112 )]
2113 pub fn tos_v4(&self) -> io::Result<u32> {
2114 self.as_socket().tos_v4()
2115 }
2116
2117 /// Deprecated. Use [`tos_v4()`] instead.
2118 ///
2119 /// [`tos_v4()`]: Self::tos_v4
2120 #[deprecated(
2121 note = "`tos` related methods have been renamed `tos_v4` since they are IPv4-specific."
2122 )]
2123 #[doc(hidden)]
2124 #[cfg(not(any(
2125 target_os = "fuchsia",
2126 target_os = "redox",
2127 target_os = "solaris",
2128 target_os = "illumos",
2129 target_os = "haiku",
2130 target_os = "wasi",
2131 )))]
2132 #[cfg_attr(
2133 docsrs,
2134 doc(cfg(not(any(
2135 target_os = "fuchsia",
2136 target_os = "redox",
2137 target_os = "solaris",
2138 target_os = "illumos",
2139 target_os = "haiku",
2140 target_os = "wasi",
2141 ))))
2142 )]
2143 pub fn tos(&self) -> io::Result<u32> {
2144 self.tos_v4()
2145 }
2146
2147 /// Sets the value for the `IP_TOS` option on this socket.
2148 ///
2149 /// This value sets the type-of-service field that is used in every packet
2150 /// sent from this socket.
2151 ///
2152 /// # Note
2153 ///
2154 /// - This may not have any effect on IPv6 sockets.
2155 /// - On Windows, `IP_TOS` is only supported on [Windows 8+ or
2156 /// Windows Server 2012+.](https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options)
2157 // https://docs.rs/socket2/0.6.1/src/socket2/socket.rs.html#1566
2158 #[cfg(not(any(
2159 target_os = "fuchsia",
2160 target_os = "redox",
2161 target_os = "solaris",
2162 target_os = "illumos",
2163 target_os = "haiku",
2164 target_os = "wasi",
2165 )))]
2166 #[cfg_attr(
2167 docsrs,
2168 doc(cfg(not(any(
2169 target_os = "fuchsia",
2170 target_os = "redox",
2171 target_os = "solaris",
2172 target_os = "illumos",
2173 target_os = "haiku",
2174 target_os = "wasi",
2175 ))))
2176 )]
2177 pub fn set_tos_v4(&self, tos: u32) -> io::Result<()> {
2178 self.as_socket().set_tos_v4(tos)
2179 }
2180
2181 /// Deprecated. Use [`set_tos_v4()`] instead.
2182 ///
2183 /// [`set_tos_v4()`]: Self::set_tos_v4
2184 #[deprecated(
2185 note = "`tos` related methods have been renamed `tos_v4` since they are IPv4-specific."
2186 )]
2187 #[doc(hidden)]
2188 #[cfg(not(any(
2189 target_os = "fuchsia",
2190 target_os = "redox",
2191 target_os = "solaris",
2192 target_os = "illumos",
2193 target_os = "haiku",
2194 target_os = "wasi",
2195 )))]
2196 #[cfg_attr(
2197 docsrs,
2198 doc(cfg(not(any(
2199 target_os = "fuchsia",
2200 target_os = "redox",
2201 target_os = "solaris",
2202 target_os = "illumos",
2203 target_os = "haiku",
2204 target_os = "wasi",
2205 ))))
2206 )]
2207 pub fn set_tos(&self, tos: u32) -> io::Result<()> {
2208 self.set_tos_v4(tos)
2209 }
2210
2211 /// Gets the value for the `SO_BINDTODEVICE` option on this socket
2212 ///
2213 /// This value gets the socket-bound device's interface name.
2214 #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux",))]
2215 #[cfg_attr(
2216 docsrs,
2217 doc(cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux",)))
2218 )]
2219 pub fn device(&self) -> io::Result<Option<Vec<u8>>> {
2220 self.as_socket().device()
2221 }
2222
2223 /// Sets the value for the `SO_BINDTODEVICE` option on this socket
2224 ///
2225 /// If a socket is bound to an interface, only packets received from that
2226 /// particular interface are processed by the socket. Note that this only
2227 /// works for some socket types, particularly `AF_INET` sockets.
2228 ///
2229 /// If `interface` is `None` or an empty string it removes the binding.
2230 #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
2231 #[cfg_attr(
2232 docsrs,
2233 doc(cfg(all(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))))
2234 )]
2235 pub fn bind_device(&self, interface: Option<&[u8]>) -> io::Result<()> {
2236 self.as_socket().bind_device(interface)
2237 }
2238
2239 /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
2240 ///
2241 /// This function specifies a new multicast group for this socket to join.
2242 /// The address must be a valid multicast address, and `interface` is the
2243 /// address of the local interface with which the system should join the
2244 /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
2245 /// interface is chosen by the system.
2246 pub fn join_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
2247 self.io.join_multicast_v4(&multiaddr, &interface)
2248 }
2249
2250 /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
2251 ///
2252 /// This function specifies a new multicast group for this socket to join.
2253 /// The address must be a valid multicast address, and `interface` is the
2254 /// index of the interface to join/leave (or 0 to indicate any interface).
2255 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
2256 self.io.join_multicast_v6(multiaddr, interface)
2257 }
2258
2259 /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
2260 ///
2261 /// For more information about this option, see [`join_multicast_v4`].
2262 ///
2263 /// [`join_multicast_v4`]: method@Self::join_multicast_v4
2264 pub fn leave_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
2265 self.io.leave_multicast_v4(&multiaddr, &interface)
2266 }
2267
2268 /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
2269 ///
2270 /// For more information about this option, see [`join_multicast_v6`].
2271 ///
2272 /// [`join_multicast_v6`]: method@Self::join_multicast_v6
2273 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
2274 self.io.leave_multicast_v6(multiaddr, interface)
2275 }
2276
2277 /// Returns the value of the `SO_ERROR` option.
2278 ///
2279 /// # Examples
2280 /// ```
2281 /// use tokio::net::UdpSocket;
2282 /// use std::io;
2283 ///
2284 /// #[tokio::main]
2285 /// async fn main() -> io::Result<()> {
2286 /// # if cfg!(miri) { return Ok(()); } // No `socket` in miri.
2287 /// // Create a socket
2288 /// let socket = UdpSocket::bind("0.0.0.0:8080").await?;
2289 ///
2290 /// if let Ok(Some(err)) = socket.take_error() {
2291 /// println!("Got error: {:?}", err);
2292 /// }
2293 ///
2294 /// Ok(())
2295 /// }
2296 /// ```
2297 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
2298 self.io.take_error()
2299 }
2300}
2301
2302impl TryFrom<std::net::UdpSocket> for UdpSocket {
2303 type Error = io::Error;
2304
2305 /// Consumes stream, returning the tokio I/O object.
2306 ///
2307 /// This is equivalent to
2308 /// [`UdpSocket::from_std(stream)`](UdpSocket::from_std).
2309 fn try_from(stream: std::net::UdpSocket) -> Result<Self, Self::Error> {
2310 Self::from_std(stream)
2311 }
2312}
2313
2314impl fmt::Debug for UdpSocket {
2315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2316 self.io.fmt(f)
2317 }
2318}
2319
2320#[cfg(not(windows))]
2321mod sys {
2322 use super::UdpSocket;
2323 use std::os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};
2324
2325 impl AsRawFd for UdpSocket {
2326 fn as_raw_fd(&self) -> RawFd {
2327 self.io.as_raw_fd()
2328 }
2329 }
2330
2331 impl AsFd for UdpSocket {
2332 fn as_fd(&self) -> BorrowedFd<'_> {
2333 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
2334 }
2335 }
2336}
2337
2338cfg_windows! {
2339 use crate::os::windows::io::{AsRawSocket, RawSocket};
2340 use crate::os::windows::io::{AsSocket, BorrowedSocket};
2341
2342 impl AsRawSocket for UdpSocket {
2343 fn as_raw_socket(&self) -> RawSocket {
2344 self.io.as_raw_socket()
2345 }
2346 }
2347
2348 impl AsSocket for UdpSocket {
2349 fn as_socket(&self) -> BorrowedSocket<'_> {
2350 unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
2351 }
2352 }
2353}