Coverage Report

Created: 2025-11-16 06:37

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