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