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 let n = ready!(self.io.registration().poll_read_io(cx, || {
808 // Safety: will not read the maybe uninitialized bytes.
809 let b = unsafe {
810 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
811 };
812
813 self.io.recv(b)
814 }))?;
815
816 // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
817 unsafe {
818 buf.assume_init(n);
819 }
820 buf.advance(n);
821 Poll::Ready(Ok(()))
822 }
823
824 /// Tries to receive a single datagram message on the socket from the remote
825 /// address to which it is connected. On success, returns the number of
826 /// bytes read.
827 ///
828 /// This method must be called with valid byte array buf of sufficient size
829 /// to hold the message bytes. If a message is too long to fit in the
830 /// supplied buffer, excess bytes may be discarded.
831 ///
832 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
833 /// returned. This function is usually paired with `readable()`.
834 ///
835 /// # Examples
836 ///
837 /// ```no_run
838 /// use tokio::net::UdpSocket;
839 /// use std::io;
840 ///
841 /// #[tokio::main]
842 /// async fn main() -> io::Result<()> {
843 /// // Connect to a peer
844 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
845 /// socket.connect("127.0.0.1:8081").await?;
846 ///
847 /// loop {
848 /// // Wait for the socket to be readable
849 /// socket.readable().await?;
850 ///
851 /// // The buffer is **not** included in the async task and will
852 /// // only exist on the stack.
853 /// let mut buf = [0; 1024];
854 ///
855 /// // Try to recv data, this may still fail with `WouldBlock`
856 /// // if the readiness event is a false positive.
857 /// match socket.try_recv(&mut buf) {
858 /// Ok(n) => {
859 /// println!("GOT {:?}", &buf[..n]);
860 /// break;
861 /// }
862 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
863 /// continue;
864 /// }
865 /// Err(e) => {
866 /// return Err(e);
867 /// }
868 /// }
869 /// }
870 ///
871 /// Ok(())
872 /// }
873 /// ```
874 pub fn try_recv(&self, buf: &mut [u8]) -> io::Result<usize> {
875 self.io
876 .registration()
877 .try_io(Interest::READABLE, || self.io.recv(buf))
878 }
879
880 cfg_io_util! {
881 /// Tries to receive data from the stream into the provided buffer, advancing the
882 /// buffer's internal cursor, returning how many bytes were read.
883 ///
884 /// This method must be called with valid byte array buf of sufficient size
885 /// to hold the message bytes. If a message is too long to fit in the
886 /// supplied buffer, excess bytes may be discarded.
887 ///
888 /// This method can be used even if `buf` is uninitialized.
889 ///
890 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
891 /// returned. This function is usually paired with `readable()`.
892 ///
893 /// # Examples
894 ///
895 /// ```no_run
896 /// use tokio::net::UdpSocket;
897 /// use std::io;
898 ///
899 /// #[tokio::main]
900 /// async fn main() -> io::Result<()> {
901 /// // Connect to a peer
902 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
903 /// socket.connect("127.0.0.1:8081").await?;
904 ///
905 /// loop {
906 /// // Wait for the socket to be readable
907 /// socket.readable().await?;
908 ///
909 /// let mut buf = Vec::with_capacity(1024);
910 ///
911 /// // Try to recv data, this may still fail with `WouldBlock`
912 /// // if the readiness event is a false positive.
913 /// match socket.try_recv_buf(&mut buf) {
914 /// Ok(n) => {
915 /// println!("GOT {:?}", &buf[..n]);
916 /// break;
917 /// }
918 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
919 /// continue;
920 /// }
921 /// Err(e) => {
922 /// return Err(e);
923 /// }
924 /// }
925 /// }
926 ///
927 /// Ok(())
928 /// }
929 /// ```
930 pub fn try_recv_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
931 self.io.registration().try_io(Interest::READABLE, || {
932 let dst = buf.chunk_mut();
933 let dst =
934 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
935
936 let n = (*self.io).recv(dst)?;
937
938 // Safety: We trust `UdpSocket::recv` to have filled up `n` bytes in the
939 // buffer.
940 unsafe {
941 buf.advance_mut(n);
942 }
943
944 Ok(n)
945 })
946 }
947
948 /// Receives a single datagram message on the socket from the remote address
949 /// to which it is connected, advancing the buffer's internal cursor,
950 /// returning how many bytes were read.
951 ///
952 /// This method must be called with valid byte array buf of sufficient size
953 /// to hold the message bytes. If a message is too long to fit in the
954 /// supplied buffer, excess bytes may be discarded.
955 ///
956 /// This method can be used even if `buf` is uninitialized.
957 ///
958 /// # Examples
959 ///
960 /// ```no_run
961 /// use tokio::net::UdpSocket;
962 /// use std::io;
963 ///
964 /// #[tokio::main]
965 /// async fn main() -> io::Result<()> {
966 /// // Connect to a peer
967 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
968 /// socket.connect("127.0.0.1:8081").await?;
969 ///
970 /// let mut buf = Vec::with_capacity(512);
971 /// let len = socket.recv_buf(&mut buf).await?;
972 ///
973 /// println!("received {} bytes {:?}", len, &buf[..len]);
974 ///
975 /// Ok(())
976 /// }
977 /// ```
978 pub async fn recv_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
979 self.io.registration().async_io(Interest::READABLE, || {
980 let dst = buf.chunk_mut();
981 let dst =
982 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
983
984 let n = (*self.io).recv(dst)?;
985
986 // Safety: We trust `UdpSocket::recv` to have filled up `n` bytes in the
987 // buffer.
988 unsafe {
989 buf.advance_mut(n);
990 }
991
992 Ok(n)
993 }).await
994 }
995
996 /// Tries to receive a single datagram message on the socket. On success,
997 /// returns the number of bytes read and the origin.
998 ///
999 /// This method must be called with valid byte array buf of sufficient size
1000 /// to hold the message bytes. If a message is too long to fit in the
1001 /// supplied buffer, excess bytes may be discarded.
1002 ///
1003 /// This method can be used even if `buf` is uninitialized.
1004 ///
1005 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1006 /// returned. This function is usually paired with `readable()`.
1007 ///
1008 /// # Notes
1009 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1010 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1011 /// Because UDP is stateless and does not validate the origin of a packet,
1012 /// the attacker does not need to be able to intercept traffic in order to interfere.
1013 /// It is important to be aware of this when designing your application-level protocol.
1014 ///
1015 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1016 ///
1017 /// # Examples
1018 ///
1019 /// ```no_run
1020 /// use tokio::net::UdpSocket;
1021 /// use std::io;
1022 ///
1023 /// #[tokio::main]
1024 /// async fn main() -> io::Result<()> {
1025 /// // Connect to a peer
1026 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1027 ///
1028 /// loop {
1029 /// // Wait for the socket to be readable
1030 /// socket.readable().await?;
1031 ///
1032 /// let mut buf = Vec::with_capacity(1024);
1033 ///
1034 /// // Try to recv data, this may still fail with `WouldBlock`
1035 /// // if the readiness event is a false positive.
1036 /// match socket.try_recv_buf_from(&mut buf) {
1037 /// Ok((n, _addr)) => {
1038 /// println!("GOT {:?}", &buf[..n]);
1039 /// break;
1040 /// }
1041 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1042 /// continue;
1043 /// }
1044 /// Err(e) => {
1045 /// return Err(e);
1046 /// }
1047 /// }
1048 /// }
1049 ///
1050 /// Ok(())
1051 /// }
1052 /// ```
1053 pub fn try_recv_buf_from<B: BufMut>(&self, buf: &mut B) -> io::Result<(usize, SocketAddr)> {
1054 self.io.registration().try_io(Interest::READABLE, || {
1055 let dst = buf.chunk_mut();
1056 let dst =
1057 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
1058
1059 let (n, addr) = (*self.io).recv_from(dst)?;
1060
1061 // Safety: We trust `UdpSocket::recv_from` to have filled up `n` bytes in the
1062 // buffer.
1063 unsafe {
1064 buf.advance_mut(n);
1065 }
1066
1067 Ok((n, addr))
1068 })
1069 }
1070
1071 /// Receives a single datagram message on the socket, advancing the
1072 /// buffer's internal cursor, returning how many bytes were read and the origin.
1073 ///
1074 /// This method must be called with valid byte array buf of sufficient size
1075 /// to hold the message bytes. If a message is too long to fit in the
1076 /// supplied buffer, excess bytes may be discarded.
1077 ///
1078 /// This method can be used even if `buf` is uninitialized.
1079 ///
1080 /// # Notes
1081 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1082 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1083 /// Because UDP is stateless and does not validate the origin of a packet,
1084 /// the attacker does not need to be able to intercept traffic in order to interfere.
1085 /// It is important to be aware of this when designing your application-level protocol.
1086 ///
1087 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1088 ///
1089 /// # Examples
1090 ///
1091 /// ```no_run
1092 /// use tokio::net::UdpSocket;
1093 /// use std::io;
1094 ///
1095 /// #[tokio::main]
1096 /// async fn main() -> io::Result<()> {
1097 /// // Connect to a peer
1098 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1099 /// socket.connect("127.0.0.1:8081").await?;
1100 ///
1101 /// let mut buf = Vec::with_capacity(512);
1102 /// let (len, addr) = socket.recv_buf_from(&mut buf).await?;
1103 ///
1104 /// println!("received {:?} bytes from {:?}", len, addr);
1105 ///
1106 /// Ok(())
1107 /// }
1108 /// ```
1109 pub async fn recv_buf_from<B: BufMut>(&self, buf: &mut B) -> io::Result<(usize, SocketAddr)> {
1110 self.io.registration().async_io(Interest::READABLE, || {
1111 let dst = buf.chunk_mut();
1112 let dst =
1113 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
1114
1115 let (n, addr) = (*self.io).recv_from(dst)?;
1116
1117 // Safety: We trust `UdpSocket::recv_from` to have filled up `n` bytes in the
1118 // buffer.
1119 unsafe {
1120 buf.advance_mut(n);
1121 }
1122
1123 Ok((n,addr))
1124 }).await
1125 }
1126 }
1127
1128 /// Sends data on the socket to the given address. On success, returns the
1129 /// number of bytes written.
1130 ///
1131 /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
1132 /// documentation for concrete examples.
1133 ///
1134 /// It is possible for `addr` to yield multiple addresses, but `send_to`
1135 /// will only send data to the first address yielded by `addr`.
1136 ///
1137 /// This will return an error when the IP version of the local socket does
1138 /// not match that returned from [`ToSocketAddrs`].
1139 ///
1140 /// [`ToSocketAddrs`]: crate::net::ToSocketAddrs
1141 ///
1142 /// # Cancel safety
1143 ///
1144 /// This method is cancel safe. If `send_to` is used as the event in a
1145 /// [`tokio::select!`](crate::select) statement and some other branch
1146 /// completes first, then it is guaranteed that the message was not sent.
1147 ///
1148 /// # Example
1149 ///
1150 /// ```no_run
1151 /// use tokio::net::UdpSocket;
1152 /// use std::io;
1153 ///
1154 /// #[tokio::main]
1155 /// async fn main() -> io::Result<()> {
1156 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1157 /// let len = socket.send_to(b"hello world", "127.0.0.1:8081").await?;
1158 ///
1159 /// println!("Sent {} bytes", len);
1160 ///
1161 /// Ok(())
1162 /// }
1163 /// ```
1164 pub async fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], target: A) -> io::Result<usize> {
1165 let mut addrs = to_socket_addrs(target).await?;
1166
1167 match addrs.next() {
1168 Some(target) => self.send_to_addr(buf, target).await,
1169 None => Err(io::Error::new(
1170 io::ErrorKind::InvalidInput,
1171 "no addresses to send data to",
1172 )),
1173 }
1174 }
1175
1176 /// Attempts to send data on the socket to a given address.
1177 ///
1178 /// Note that on multiple calls to a `poll_*` method in the send direction, only the
1179 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1180 /// receive a wakeup.
1181 ///
1182 /// # Return value
1183 ///
1184 /// The function returns:
1185 ///
1186 /// * `Poll::Pending` if the socket is not ready to write
1187 /// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent.
1188 /// * `Poll::Ready(Err(e))` if an error is encountered.
1189 ///
1190 /// # Errors
1191 ///
1192 /// This function may encounter any standard I/O error except `WouldBlock`.
1193 pub fn poll_send_to(
1194 &self,
1195 cx: &mut Context<'_>,
1196 buf: &[u8],
1197 target: SocketAddr,
1198 ) -> Poll<io::Result<usize>> {
1199 self.io
1200 .registration()
1201 .poll_write_io(cx, || self.io.send_to(buf, target))
1202 }
1203
1204 /// Tries to send data on the socket to the given address, but if the send is
1205 /// blocked this will return right away.
1206 ///
1207 /// This function is usually paired with `writable()`.
1208 ///
1209 /// # Returns
1210 ///
1211 /// If successful, returns the number of bytes sent
1212 ///
1213 /// Users should ensure that when the remote cannot receive, the
1214 /// [`ErrorKind::WouldBlock`] is properly handled. An error can also occur
1215 /// if the IP version of the socket does not match that of `target`.
1216 ///
1217 /// [`ErrorKind::WouldBlock`]: std::io::ErrorKind::WouldBlock
1218 ///
1219 /// # Example
1220 ///
1221 /// ```no_run
1222 /// use tokio::net::UdpSocket;
1223 /// use std::error::Error;
1224 /// use std::io;
1225 ///
1226 /// #[tokio::main]
1227 /// async fn main() -> Result<(), Box<dyn Error>> {
1228 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1229 ///
1230 /// let dst = "127.0.0.1:8081".parse()?;
1231 ///
1232 /// loop {
1233 /// socket.writable().await?;
1234 ///
1235 /// match socket.try_send_to(&b"hello world"[..], dst) {
1236 /// Ok(sent) => {
1237 /// println!("sent {} bytes", sent);
1238 /// break;
1239 /// }
1240 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1241 /// // Writable false positive.
1242 /// continue;
1243 /// }
1244 /// Err(e) => return Err(e.into()),
1245 /// }
1246 /// }
1247 ///
1248 /// Ok(())
1249 /// }
1250 /// ```
1251 pub fn try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
1252 self.io
1253 .registration()
1254 .try_io(Interest::WRITABLE, || self.io.send_to(buf, target))
1255 }
1256
1257 async fn send_to_addr(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
1258 self.io
1259 .registration()
1260 .async_io(Interest::WRITABLE, || self.io.send_to(buf, target))
1261 .await
1262 }
1263
1264 /// Receives a single datagram message on the socket. On success, returns
1265 /// the number of bytes read and the origin.
1266 ///
1267 /// The function must be called with valid byte array `buf` of sufficient
1268 /// size to hold the message bytes. If a message is too long to fit in the
1269 /// supplied buffer, excess bytes may be discarded.
1270 ///
1271 /// # Cancel safety
1272 ///
1273 /// This method is cancel safe. If `recv_from` is used as the event in a
1274 /// [`tokio::select!`](crate::select) statement and some other branch
1275 /// completes first, it is guaranteed that no messages were received on this
1276 /// socket.
1277 ///
1278 /// # Example
1279 ///
1280 /// ```no_run
1281 /// use tokio::net::UdpSocket;
1282 /// use std::io;
1283 ///
1284 /// #[tokio::main]
1285 /// async fn main() -> io::Result<()> {
1286 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1287 ///
1288 /// let mut buf = vec![0u8; 32];
1289 /// let (len, addr) = socket.recv_from(&mut buf).await?;
1290 ///
1291 /// println!("received {:?} bytes from {:?}", len, addr);
1292 ///
1293 /// Ok(())
1294 /// }
1295 /// ```
1296 ///
1297 /// # Notes
1298 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1299 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1300 /// Because UDP is stateless and does not validate the origin of a packet,
1301 /// the attacker does not need to be able to intercept traffic in order to interfere.
1302 /// It is important to be aware of this when designing your application-level protocol.
1303 ///
1304 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1305 pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1306 self.io
1307 .registration()
1308 .async_io(Interest::READABLE, || self.io.recv_from(buf))
1309 .await
1310 }
1311
1312 /// Attempts to receive a single datagram on the socket.
1313 ///
1314 /// Note that on multiple calls to a `poll_*` method in the recv direction, only the
1315 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1316 /// receive a wakeup.
1317 ///
1318 /// # Return value
1319 ///
1320 /// The function returns:
1321 ///
1322 /// * `Poll::Pending` if the socket is not ready to read
1323 /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1324 /// * `Poll::Ready(Err(e))` if an error is encountered.
1325 ///
1326 /// # Errors
1327 ///
1328 /// This function may encounter any standard I/O error except `WouldBlock`.
1329 ///
1330 /// # Notes
1331 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1332 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1333 /// Because UDP is stateless and does not validate the origin of a packet,
1334 /// the attacker does not need to be able to intercept traffic in order to interfere.
1335 /// It is important to be aware of this when designing your application-level protocol.
1336 ///
1337 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1338 pub fn poll_recv_from(
1339 &self,
1340 cx: &mut Context<'_>,
1341 buf: &mut ReadBuf<'_>,
1342 ) -> Poll<io::Result<SocketAddr>> {
1343 let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1344 // Safety: will not read the maybe uninitialized bytes.
1345 let b = unsafe {
1346 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1347 };
1348
1349 self.io.recv_from(b)
1350 }))?;
1351
1352 // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1353 unsafe {
1354 buf.assume_init(n);
1355 }
1356 buf.advance(n);
1357 Poll::Ready(Ok(addr))
1358 }
1359
1360 /// Tries to receive a single datagram message on the socket. On success,
1361 /// returns the number of bytes read and the origin.
1362 ///
1363 /// This method must be called with valid byte array buf of sufficient size
1364 /// to hold the message bytes. If a message is too long to fit in the
1365 /// supplied buffer, excess bytes may be discarded.
1366 ///
1367 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1368 /// returned. This function is usually paired with `readable()`.
1369 ///
1370 /// # Notes
1371 ///
1372 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1373 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1374 /// Because UDP is stateless and does not validate the origin of a packet,
1375 /// the attacker does not need to be able to intercept traffic in order to interfere.
1376 /// It is important to be aware of this when designing your application-level protocol.
1377 ///
1378 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1379 ///
1380 /// # Examples
1381 ///
1382 /// ```no_run
1383 /// use tokio::net::UdpSocket;
1384 /// use std::io;
1385 ///
1386 /// #[tokio::main]
1387 /// async fn main() -> io::Result<()> {
1388 /// // Connect to a peer
1389 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1390 ///
1391 /// loop {
1392 /// // Wait for the socket to be readable
1393 /// socket.readable().await?;
1394 ///
1395 /// // The buffer is **not** included in the async task and will
1396 /// // only exist on the stack.
1397 /// let mut buf = [0; 1024];
1398 ///
1399 /// // Try to recv data, this may still fail with `WouldBlock`
1400 /// // if the readiness event is a false positive.
1401 /// match socket.try_recv_from(&mut buf) {
1402 /// Ok((n, _addr)) => {
1403 /// println!("GOT {:?}", &buf[..n]);
1404 /// break;
1405 /// }
1406 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1407 /// continue;
1408 /// }
1409 /// Err(e) => {
1410 /// return Err(e);
1411 /// }
1412 /// }
1413 /// }
1414 ///
1415 /// Ok(())
1416 /// }
1417 /// ```
1418 pub fn try_recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1419 self.io
1420 .registration()
1421 .try_io(Interest::READABLE, || self.io.recv_from(buf))
1422 }
1423
1424 /// Tries to read or write from the socket using a user-provided IO operation.
1425 ///
1426 /// If the socket is ready, the provided closure is called. The closure
1427 /// should attempt to perform IO operation on the socket by manually
1428 /// calling the appropriate syscall. If the operation fails because the
1429 /// socket is not actually ready, then the closure should return a
1430 /// `WouldBlock` error and the readiness flag is cleared. The return value
1431 /// of the closure is then returned by `try_io`.
1432 ///
1433 /// If the socket is not ready, then the closure is not called
1434 /// and a `WouldBlock` error is returned.
1435 ///
1436 /// The closure should only return a `WouldBlock` error if it has performed
1437 /// an IO operation on the socket that failed due to the socket not being
1438 /// ready. Returning a `WouldBlock` error in any other situation will
1439 /// incorrectly clear the readiness flag, which can cause the socket to
1440 /// behave incorrectly.
1441 ///
1442 /// The closure should not perform the IO operation using any of the methods
1443 /// defined on the Tokio `UdpSocket` type, as this will mess with the
1444 /// readiness flag and can cause the socket to behave incorrectly.
1445 ///
1446 /// This method is not intended to be used with combined interests.
1447 /// The closure should perform only one type of IO operation, so it should not
1448 /// require more than one ready state. This method may panic or sleep forever
1449 /// if it is called with a combined interest.
1450 ///
1451 /// Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.
1452 ///
1453 /// [`readable()`]: UdpSocket::readable()
1454 /// [`writable()`]: UdpSocket::writable()
1455 /// [`ready()`]: UdpSocket::ready()
1456 pub fn try_io<R>(
1457 &self,
1458 interest: Interest,
1459 f: impl FnOnce() -> io::Result<R>,
1460 ) -> io::Result<R> {
1461 self.io
1462 .registration()
1463 .try_io(interest, || self.io.try_io(f))
1464 }
1465
1466 /// Reads or writes from the socket using a user-provided IO operation.
1467 ///
1468 /// The readiness of the socket is awaited and when the socket is ready,
1469 /// the provided closure is called. The closure should attempt to perform
1470 /// IO operation on the socket by manually calling the appropriate syscall.
1471 /// If the operation fails because the socket is not actually ready,
1472 /// then the closure should return a `WouldBlock` error. In such case the
1473 /// readiness flag is cleared and the socket readiness is awaited again.
1474 /// This loop is repeated until the closure returns an `Ok` or an error
1475 /// other than `WouldBlock`.
1476 ///
1477 /// The closure should only return a `WouldBlock` error if it has performed
1478 /// an IO operation on the socket that failed due to the socket not being
1479 /// ready. Returning a `WouldBlock` error in any other situation will
1480 /// incorrectly clear the readiness flag, which can cause the socket to
1481 /// behave incorrectly.
1482 ///
1483 /// The closure should not perform the IO operation using any of the methods
1484 /// defined on the Tokio `UdpSocket` type, as this will mess with the
1485 /// readiness flag and can cause the socket to behave incorrectly.
1486 ///
1487 /// This method is not intended to be used with combined interests.
1488 /// The closure should perform only one type of IO operation, so it should not
1489 /// require more than one ready state. This method may panic or sleep forever
1490 /// if it is called with a combined interest.
1491 pub async fn async_io<R>(
1492 &self,
1493 interest: Interest,
1494 mut f: impl FnMut() -> io::Result<R>,
1495 ) -> io::Result<R> {
1496 self.io
1497 .registration()
1498 .async_io(interest, || self.io.try_io(&mut f))
1499 .await
1500 }
1501
1502 /// Receives data from the socket, without removing it from the input queue.
1503 /// On success, returns the number of bytes read and the address from whence
1504 /// the data came.
1505 ///
1506 /// # Notes
1507 ///
1508 /// On Windows, if the data is larger than the buffer specified, the buffer
1509 /// is filled with the first part of the data, and `peek_from` returns the error
1510 /// WSAEMSGSIZE(10040). The excess data is lost.
1511 /// Make sure to always use a sufficiently large buffer to hold the
1512 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1513 ///
1514 /// MacOS will return an error if you pass a zero-sized buffer.
1515 ///
1516 /// If you're merely interested in learning the sender of the data at the head of the queue,
1517 /// try [`peek_sender`].
1518 ///
1519 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1520 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1521 /// Because UDP is stateless and does not validate the origin of a packet,
1522 /// the attacker does not need to be able to intercept traffic in order to interfere.
1523 /// It is important to be aware of this when designing your application-level protocol.
1524 ///
1525 /// # Examples
1526 ///
1527 /// ```no_run
1528 /// use tokio::net::UdpSocket;
1529 /// use std::io;
1530 ///
1531 /// #[tokio::main]
1532 /// async fn main() -> io::Result<()> {
1533 /// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1534 ///
1535 /// let mut buf = vec![0u8; 32];
1536 /// let (len, addr) = socket.peek_from(&mut buf).await?;
1537 ///
1538 /// println!("peeked {:?} bytes from {:?}", len, addr);
1539 ///
1540 /// Ok(())
1541 /// }
1542 /// ```
1543 ///
1544 /// [`peek_sender`]: method@Self::peek_sender
1545 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1546 pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1547 self.io
1548 .registration()
1549 .async_io(Interest::READABLE, || self.io.peek_from(buf))
1550 .await
1551 }
1552
1553 /// Receives data from the socket, without removing it from the input queue.
1554 /// On success, returns the sending address of the datagram.
1555 ///
1556 /// # Notes
1557 ///
1558 /// Note that on multiple calls to a `poll_*` method in the recv direction, only the
1559 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1560 /// receive a wakeup
1561 ///
1562 /// On Windows, if the data is larger than the buffer specified, the buffer
1563 /// is filled with the first part of the data, and peek returns the error
1564 /// WSAEMSGSIZE(10040). The excess data is lost.
1565 /// Make sure to always use a sufficiently large buffer to hold the
1566 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1567 ///
1568 /// MacOS will return an error if you pass a zero-sized buffer.
1569 ///
1570 /// If you're merely interested in learning the sender of the data at the head of the queue,
1571 /// try [`poll_peek_sender`].
1572 ///
1573 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1574 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1575 /// Because UDP is stateless and does not validate the origin of a packet,
1576 /// the attacker does not need to be able to intercept traffic in order to interfere.
1577 /// It is important to be aware of this when designing your application-level protocol.
1578 ///
1579 /// # Return value
1580 ///
1581 /// The function returns:
1582 ///
1583 /// * `Poll::Pending` if the socket is not ready to read
1584 /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1585 /// * `Poll::Ready(Err(e))` if an error is encountered.
1586 ///
1587 /// # Errors
1588 ///
1589 /// This function may encounter any standard I/O error except `WouldBlock`.
1590 ///
1591 /// [`poll_peek_sender`]: method@Self::poll_peek_sender
1592 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1593 pub fn poll_peek_from(
1594 &self,
1595 cx: &mut Context<'_>,
1596 buf: &mut ReadBuf<'_>,
1597 ) -> Poll<io::Result<SocketAddr>> {
1598 let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1599 // Safety: will not read the maybe uninitialized bytes.
1600 let b = unsafe {
1601 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1602 };
1603
1604 self.io.peek_from(b)
1605 }))?;
1606
1607 // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1608 unsafe {
1609 buf.assume_init(n);
1610 }
1611 buf.advance(n);
1612 Poll::Ready(Ok(addr))
1613 }
1614
1615 /// Tries to receive data on the socket without removing it from the input queue.
1616 /// On success, returns the number of bytes read and the sending address of the
1617 /// datagram.
1618 ///
1619 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1620 /// returned. This function is usually paired with `readable()`.
1621 ///
1622 /// # Notes
1623 ///
1624 /// On Windows, if the data is larger than the buffer specified, the buffer
1625 /// is filled with the first part of the data, and peek returns the error
1626 /// WSAEMSGSIZE(10040). The excess data is lost.
1627 /// Make sure to always use a sufficiently large buffer to hold the
1628 /// maximum UDP packet size, which can be up to 65536 bytes in size.
1629 ///
1630 /// MacOS will return an error if you pass a zero-sized buffer.
1631 ///
1632 /// If you're merely interested in learning the sender of the data at the head of the queue,
1633 /// try [`try_peek_sender`].
1634 ///
1635 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1636 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1637 /// Because UDP is stateless and does not validate the origin of a packet,
1638 /// the attacker does not need to be able to intercept traffic in order to interfere.
1639 /// It is important to be aware of this when designing your application-level protocol.
1640 ///
1641 /// [`try_peek_sender`]: method@Self::try_peek_sender
1642 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1643 pub fn try_peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1644 self.io
1645 .registration()
1646 .try_io(Interest::READABLE, || self.io.peek_from(buf))
1647 }
1648
1649 /// Retrieve the sender of the data at the head of the input queue, waiting if empty.
1650 ///
1651 /// This is equivalent to calling [`peek_from`] with a zero-sized buffer,
1652 /// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
1653 ///
1654 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1655 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1656 /// Because UDP is stateless and does not validate the origin of a packet,
1657 /// the attacker does not need to be able to intercept traffic in order to interfere.
1658 /// It is important to be aware of this when designing your application-level protocol.
1659 ///
1660 /// [`peek_from`]: method@Self::peek_from
1661 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1662 pub async fn peek_sender(&self) -> io::Result<SocketAddr> {
1663 self.io
1664 .registration()
1665 .async_io(Interest::READABLE, || self.peek_sender_inner())
1666 .await
1667 }
1668
1669 /// Retrieve the sender of the data at the head of the input queue,
1670 /// scheduling a wakeup if empty.
1671 ///
1672 /// This is equivalent to calling [`poll_peek_from`] with a zero-sized buffer,
1673 /// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
1674 ///
1675 /// # Notes
1676 ///
1677 /// Note that on multiple calls to a `poll_*` method in the recv direction, only the
1678 /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1679 /// receive a wakeup.
1680 ///
1681 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1682 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1683 /// Because UDP is stateless and does not validate the origin of a packet,
1684 /// the attacker does not need to be able to intercept traffic in order to interfere.
1685 /// It is important to be aware of this when designing your application-level protocol.
1686 ///
1687 /// [`poll_peek_from`]: method@Self::poll_peek_from
1688 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1689 pub fn poll_peek_sender(&self, cx: &mut Context<'_>) -> Poll<io::Result<SocketAddr>> {
1690 self.io
1691 .registration()
1692 .poll_read_io(cx, || self.peek_sender_inner())
1693 }
1694
1695 /// Try to retrieve the sender of the data at the head of the input queue.
1696 ///
1697 /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1698 /// returned. This function is usually paired with `readable()`.
1699 ///
1700 /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1701 /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1702 /// Because UDP is stateless and does not validate the origin of a packet,
1703 /// the attacker does not need to be able to intercept traffic in order to interfere.
1704 /// It is important to be aware of this when designing your application-level protocol.
1705 ///
1706 /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1707 pub fn try_peek_sender(&self) -> io::Result<SocketAddr> {
1708 self.io
1709 .registration()
1710 .try_io(Interest::READABLE, || self.peek_sender_inner())
1711 }
1712
1713 #[inline]
1714 fn peek_sender_inner(&self) -> io::Result<SocketAddr> {
1715 self.io.try_io(|| {
1716 self.as_socket()
1717 .peek_sender()?
1718 // May be `None` if the platform doesn't populate the sender for some reason.
1719 // In testing, that only occurred on macOS if you pass a zero-sized buffer,
1720 // but the implementation of `Socket::peek_sender()` covers that.
1721 .as_socket()
1722 .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "sender not available"))
1723 })
1724 }
1725
1726 /// Gets the value of the `SO_BROADCAST` option for this socket.
1727 ///
1728 /// For more information about this option, see [`set_broadcast`].
1729 ///
1730 /// [`set_broadcast`]: method@Self::set_broadcast
1731 pub fn broadcast(&self) -> io::Result<bool> {
1732 self.io.broadcast()
1733 }
1734
1735 /// Sets the value of the `SO_BROADCAST` option for this socket.
1736 ///
1737 /// When enabled, this socket is allowed to send packets to a broadcast
1738 /// address.
1739 pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
1740 self.io.set_broadcast(on)
1741 }
1742
1743 /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
1744 ///
1745 /// For more information about this option, see [`set_multicast_loop_v4`].
1746 ///
1747 /// [`set_multicast_loop_v4`]: method@Self::set_multicast_loop_v4
1748 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
1749 self.io.multicast_loop_v4()
1750 }
1751
1752 /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
1753 ///
1754 /// If enabled, multicast packets will be looped back to the local socket.
1755 ///
1756 /// # Note
1757 ///
1758 /// This may not have any affect on IPv6 sockets.
1759 pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> {
1760 self.io.set_multicast_loop_v4(on)
1761 }
1762
1763 /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
1764 ///
1765 /// For more information about this option, see [`set_multicast_ttl_v4`].
1766 ///
1767 /// [`set_multicast_ttl_v4`]: method@Self::set_multicast_ttl_v4
1768 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
1769 self.io.multicast_ttl_v4()
1770 }
1771
1772 /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
1773 ///
1774 /// Indicates the time-to-live value of outgoing multicast packets for
1775 /// this socket. The default value is 1 which means that multicast packets
1776 /// don't leave the local network unless explicitly requested.
1777 ///
1778 /// # Note
1779 ///
1780 /// This may not have any affect on IPv6 sockets.
1781 pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> {
1782 self.io.set_multicast_ttl_v4(ttl)
1783 }
1784
1785 /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1786 ///
1787 /// For more information about this option, see [`set_multicast_loop_v6`].
1788 ///
1789 /// [`set_multicast_loop_v6`]: method@Self::set_multicast_loop_v6
1790 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
1791 self.io.multicast_loop_v6()
1792 }
1793
1794 /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1795 ///
1796 /// Controls whether this socket sees the multicast packets it sends itself.
1797 ///
1798 /// # Note
1799 ///
1800 /// This may not have any affect on IPv4 sockets.
1801 pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> {
1802 self.io.set_multicast_loop_v6(on)
1803 }
1804
1805 /// Gets the value of the `IP_TTL` option for this socket.
1806 ///
1807 /// For more information about this option, see [`set_ttl`].
1808 ///
1809 /// [`set_ttl`]: method@Self::set_ttl
1810 ///
1811 /// # Examples
1812 ///
1813 /// ```no_run
1814 /// use tokio::net::UdpSocket;
1815 /// # use std::io;
1816 ///
1817 /// # async fn dox() -> io::Result<()> {
1818 /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
1819 ///
1820 /// println!("{:?}", sock.ttl()?);
1821 /// # Ok(())
1822 /// # }
1823 /// ```
1824 pub fn ttl(&self) -> io::Result<u32> {
1825 self.io.ttl()
1826 }
1827
1828 /// Sets the value for the `IP_TTL` option on this socket.
1829 ///
1830 /// This value sets the time-to-live field that is used in every packet sent
1831 /// from this socket.
1832 ///
1833 /// # Examples
1834 ///
1835 /// ```no_run
1836 /// use tokio::net::UdpSocket;
1837 /// # use std::io;
1838 ///
1839 /// # async fn dox() -> io::Result<()> {
1840 /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
1841 /// sock.set_ttl(60)?;
1842 ///
1843 /// # Ok(())
1844 /// # }
1845 /// ```
1846 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
1847 self.io.set_ttl(ttl)
1848 }
1849
1850 /// Gets the value of the `IP_TOS` option for this socket.
1851 ///
1852 /// For more information about this option, see [`set_tos`].
1853 ///
1854 /// **NOTE:** On Windows, `IP_TOS` is only supported on [Windows 8+ or
1855 /// Windows Server 2012+.](https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options)
1856 ///
1857 /// [`set_tos`]: Self::set_tos
1858 // https://docs.rs/socket2/0.5.3/src/socket2/socket.rs.html#1464
1859 #[cfg(not(any(
1860 target_os = "fuchsia",
1861 target_os = "redox",
1862 target_os = "solaris",
1863 target_os = "illumos",
1864 )))]
1865 #[cfg_attr(
1866 docsrs,
1867 doc(cfg(not(any(
1868 target_os = "fuchsia",
1869 target_os = "redox",
1870 target_os = "solaris",
1871 target_os = "illumos",
1872 ))))
1873 )]
1874 pub fn tos(&self) -> io::Result<u32> {
1875 self.as_socket().tos()
1876 }
1877
1878 /// Sets the value for the `IP_TOS` option on this socket.
1879 ///
1880 /// This value sets the type-of-service field that is used in every packet
1881 /// sent from this socket.
1882 ///
1883 /// **NOTE:** On Windows, `IP_TOS` is only supported on [Windows 8+ or
1884 /// Windows Server 2012+.](https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options)
1885 // https://docs.rs/socket2/0.5.3/src/socket2/socket.rs.html#1446
1886 #[cfg(not(any(
1887 target_os = "fuchsia",
1888 target_os = "redox",
1889 target_os = "solaris",
1890 target_os = "illumos",
1891 )))]
1892 #[cfg_attr(
1893 docsrs,
1894 doc(cfg(not(any(
1895 target_os = "fuchsia",
1896 target_os = "redox",
1897 target_os = "solaris",
1898 target_os = "illumos",
1899 ))))
1900 )]
1901 pub fn set_tos(&self, tos: u32) -> io::Result<()> {
1902 self.as_socket().set_tos(tos)
1903 }
1904
1905 /// Gets the value for the `SO_BINDTODEVICE` option on this socket
1906 ///
1907 /// This value gets the socket-bound device's interface name.
1908 #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux",))]
1909 #[cfg_attr(
1910 docsrs,
1911 doc(cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux",)))
1912 )]
1913 pub fn device(&self) -> io::Result<Option<Vec<u8>>> {
1914 self.as_socket().device()
1915 }
1916
1917 /// Sets the value for the `SO_BINDTODEVICE` option on this socket
1918 ///
1919 /// If a socket is bound to an interface, only packets received from that
1920 /// particular interface are processed by the socket. Note that this only
1921 /// works for some socket types, particularly `AF_INET` sockets.
1922 ///
1923 /// If `interface` is `None` or an empty string it removes the binding.
1924 #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
1925 #[cfg_attr(
1926 docsrs,
1927 doc(cfg(all(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))))
1928 )]
1929 pub fn bind_device(&self, interface: Option<&[u8]>) -> io::Result<()> {
1930 self.as_socket().bind_device(interface)
1931 }
1932
1933 /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
1934 ///
1935 /// This function specifies a new multicast group for this socket to join.
1936 /// The address must be a valid multicast address, and `interface` is the
1937 /// address of the local interface with which the system should join the
1938 /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
1939 /// interface is chosen by the system.
1940 pub fn join_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
1941 self.io.join_multicast_v4(&multiaddr, &interface)
1942 }
1943
1944 /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
1945 ///
1946 /// This function specifies a new multicast group for this socket to join.
1947 /// The address must be a valid multicast address, and `interface` is the
1948 /// index of the interface to join/leave (or 0 to indicate any interface).
1949 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
1950 self.io.join_multicast_v6(multiaddr, interface)
1951 }
1952
1953 /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
1954 ///
1955 /// For more information about this option, see [`join_multicast_v4`].
1956 ///
1957 /// [`join_multicast_v4`]: method@Self::join_multicast_v4
1958 pub fn leave_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
1959 self.io.leave_multicast_v4(&multiaddr, &interface)
1960 }
1961
1962 /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
1963 ///
1964 /// For more information about this option, see [`join_multicast_v6`].
1965 ///
1966 /// [`join_multicast_v6`]: method@Self::join_multicast_v6
1967 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
1968 self.io.leave_multicast_v6(multiaddr, interface)
1969 }
1970
1971 /// Returns the value of the `SO_ERROR` option.
1972 ///
1973 /// # Examples
1974 /// ```
1975 /// use tokio::net::UdpSocket;
1976 /// use std::io;
1977 ///
1978 /// #[tokio::main]
1979 /// async fn main() -> io::Result<()> {
1980 /// // Create a socket
1981 /// let socket = UdpSocket::bind("0.0.0.0:8080").await?;
1982 ///
1983 /// if let Ok(Some(err)) = socket.take_error() {
1984 /// println!("Got error: {:?}", err);
1985 /// }
1986 ///
1987 /// Ok(())
1988 /// }
1989 /// ```
1990 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1991 self.io.take_error()
1992 }
1993}
1994
1995impl TryFrom<std::net::UdpSocket> for UdpSocket {
1996 type Error = io::Error;
1997
1998 /// Consumes stream, returning the tokio I/O object.
1999 ///
2000 /// This is equivalent to
2001 /// [`UdpSocket::from_std(stream)`](UdpSocket::from_std).
2002 fn try_from(stream: std::net::UdpSocket) -> Result<Self, Self::Error> {
2003 Self::from_std(stream)
2004 }
2005}
2006
2007impl fmt::Debug for UdpSocket {
2008 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2009 self.io.fmt(f)
2010 }
2011}
2012
2013#[cfg(unix)]
2014mod sys {
2015 use super::UdpSocket;
2016 use std::os::unix::prelude::*;
2017
2018 impl AsRawFd for UdpSocket {
2019 fn as_raw_fd(&self) -> RawFd {
2020 self.io.as_raw_fd()
2021 }
2022 }
2023
2024 impl AsFd for UdpSocket {
2025 fn as_fd(&self) -> BorrowedFd<'_> {
2026 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
2027 }
2028 }
2029}
2030
2031cfg_windows! {
2032 use crate::os::windows::io::{AsRawSocket, RawSocket};
2033 use crate::os::windows::io::{AsSocket, BorrowedSocket};
2034
2035 impl AsRawSocket for UdpSocket {
2036 fn as_raw_socket(&self) -> RawSocket {
2037 self.io.as_raw_socket()
2038 }
2039 }
2040
2041 impl AsSocket for UdpSocket {
2042 fn as_socket(&self) -> BorrowedSocket<'_> {
2043 unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
2044 }
2045 }
2046}
2047