Coverage Report

Created: 2026-03-31 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.50.0/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
    /// use tokio::net::UdpSocket;
139
    /// use std::io;
140
    ///
141
    /// #[tokio::main]
142
    /// async fn main() -> io::Result<()> {
143
    /// #   if cfg!(miri) { return Ok(()); } // No `socket` in miri.
144
    ///     let sock = UdpSocket::bind("0.0.0.0:8080").await?;
145
    ///     // use `sock`
146
    /// #   let _ = sock;
147
    ///     Ok(())
148
    /// }
149
    /// ```
150
0
    pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
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
        }))
167
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
    /// use tokio::net::UdpSocket;
307
    ///
308
    /// # use std::{io, net::SocketAddr};
309
    /// # #[tokio::main]
310
    /// # async fn main() -> io::Result<()> {
311
    /// # if cfg!(miri) { return Ok(()); } // No `socket` in miri.
312
    /// let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
313
    /// let peer = "127.0.0.1:11100".parse::<SocketAddr>().unwrap();
314
    /// let sock = UdpSocket::bind(addr).await?;
315
    /// sock.connect(peer).await?;
316
    /// assert_eq!(peer, sock.peer_addr()?);
317
    /// #    Ok(())
318
    /// # }
319
    /// ```
320
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 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
    ///
1565
    /// # Notes
1566
    ///
1567
    /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1568
    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1569
    /// receive a wakeup
1570
    ///
1571
    /// On Windows, if the data is larger than the buffer specified, the buffer
1572
    /// is filled with the first part of the data, and peek returns the error
1573
    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1574
    /// Make sure to always use a sufficiently large buffer to hold the
1575
    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1576
    ///
1577
    /// MacOS will return an error if you pass a zero-sized buffer.
1578
    ///
1579
    /// If you're merely interested in learning the sender of the data at the head of the queue,
1580
    /// try [`poll_peek_sender`].
1581
    ///
1582
    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1583
    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1584
    /// Because UDP is stateless and does not validate the origin of a packet,
1585
    /// the attacker does not need to be able to intercept traffic in order to interfere.
1586
    /// It is important to be aware of this when designing your application-level protocol.
1587
    ///
1588
    /// # Return value
1589
    ///
1590
    /// The function returns:
1591
    ///
1592
    /// * `Poll::Pending` if the socket is not ready to read
1593
    /// * `Poll::Ready(Ok(()))` reads data into `ReadBuf` if the socket is ready
1594
    /// * `Poll::Ready(Err(e))` if an error is encountered.
1595
    ///
1596
    /// # Errors
1597
    ///
1598
    /// This function may encounter any standard I/O error except `WouldBlock`.
1599
    ///
1600
    /// [`poll_peek_sender`]: method@Self::poll_peek_sender
1601
    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1602
0
    pub fn poll_peek(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
1603
        #[allow(clippy::blocks_in_conditions)]
1604
0
        let n = ready!(self.io.registration().poll_read_io(cx, || {
1605
            // Safety: will not read the maybe uninitialized bytes.
1606
0
            let b = unsafe {
1607
0
                &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1608
            };
1609
1610
0
            self.io.peek(b)
1611
0
        }))?;
1612
1613
        // Safety: We trust `peek` to have filled up `n` bytes in the buffer.
1614
0
        unsafe {
1615
0
            buf.assume_init(n);
1616
0
        }
1617
0
        buf.advance(n);
1618
0
        Poll::Ready(Ok(()))
1619
0
    }
1620
1621
    /// Tries to receive data on the connected address without removing it from the input queue.
1622
    /// On success, returns the number of bytes read.
1623
    ///
1624
    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1625
    /// returned. This function is usually paired with `readable()`.
1626
    ///
1627
    /// # Notes
1628
    ///
1629
    /// On Windows, if the data is larger than the buffer specified, the buffer
1630
    /// is filled with the first part of the data, and peek returns the error
1631
    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1632
    /// Make sure to always use a sufficiently large buffer to hold the
1633
    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1634
    ///
1635
    /// MacOS will return an error if you pass a zero-sized buffer.
1636
    ///
1637
    /// If you're merely interested in learning the sender of the data at the head of the queue,
1638
    /// try [`try_peek_sender`].
1639
    ///
1640
    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1641
    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1642
    /// Because UDP is stateless and does not validate the origin of a packet,
1643
    /// the attacker does not need to be able to intercept traffic in order to interfere.
1644
    /// It is important to be aware of this when designing your application-level protocol.
1645
    ///
1646
    /// [`try_peek_sender`]: method@Self::try_peek_sender
1647
    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1648
0
    pub fn try_peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1649
0
        self.io
1650
0
            .registration()
1651
0
            .try_io(Interest::READABLE, || self.io.peek(buf))
1652
0
    }
1653
1654
    /// Receives data from the socket, without removing it from the input queue.
1655
    /// On success, returns the number of bytes read and the address from whence
1656
    /// the data came.
1657
    ///
1658
    /// # Notes
1659
    ///
1660
    /// On Windows, if the data is larger than the buffer specified, the buffer
1661
    /// is filled with the first part of the data, and `peek_from` returns the error
1662
    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1663
    /// Make sure to always use a sufficiently large buffer to hold the
1664
    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1665
    ///
1666
    /// MacOS will return an error if you pass a zero-sized buffer.
1667
    ///
1668
    /// If you're merely interested in learning the sender of the data at the head of the queue,
1669
    /// try [`peek_sender`].
1670
    ///
1671
    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1672
    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1673
    /// Because UDP is stateless and does not validate the origin of a packet,
1674
    /// the attacker does not need to be able to intercept traffic in order to interfere.
1675
    /// It is important to be aware of this when designing your application-level protocol.
1676
    ///
1677
    /// # Examples
1678
    ///
1679
    /// ```no_run
1680
    /// use tokio::net::UdpSocket;
1681
    /// use std::io;
1682
    ///
1683
    /// #[tokio::main]
1684
    /// async fn main() -> io::Result<()> {
1685
    ///     let socket = UdpSocket::bind("127.0.0.1:8080").await?;
1686
    ///
1687
    ///     let mut buf = vec![0u8; 32];
1688
    ///     let (len, addr) = socket.peek_from(&mut buf).await?;
1689
    ///
1690
    ///     println!("peeked {:?} bytes from {:?}", len, addr);
1691
    ///
1692
    ///     Ok(())
1693
    /// }
1694
    /// ```
1695
    ///
1696
    /// [`peek_sender`]: method@Self::peek_sender
1697
    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1698
0
    pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1699
0
        self.io
1700
0
            .registration()
1701
0
            .async_io(Interest::READABLE, || self.io.peek_from(buf))
1702
0
            .await
1703
0
    }
1704
1705
    /// Receives data from the socket, without removing it from the input queue.
1706
    /// On success, returns the sending address of the datagram.
1707
    ///
1708
    /// # Notes
1709
    ///
1710
    /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1711
    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1712
    /// receive a wakeup
1713
    ///
1714
    /// On Windows, if the data is larger than the buffer specified, the buffer
1715
    /// is filled with the first part of the data, and peek returns the error
1716
    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1717
    /// Make sure to always use a sufficiently large buffer to hold the
1718
    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1719
    ///
1720
    /// MacOS will return an error if you pass a zero-sized buffer.
1721
    ///
1722
    /// If you're merely interested in learning the sender of the data at the head of the queue,
1723
    /// try [`poll_peek_sender`].
1724
    ///
1725
    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1726
    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1727
    /// Because UDP is stateless and does not validate the origin of a packet,
1728
    /// the attacker does not need to be able to intercept traffic in order to interfere.
1729
    /// It is important to be aware of this when designing your application-level protocol.
1730
    ///
1731
    /// # Return value
1732
    ///
1733
    /// The function returns:
1734
    ///
1735
    /// * `Poll::Pending` if the socket is not ready to read
1736
    /// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
1737
    /// * `Poll::Ready(Err(e))` if an error is encountered.
1738
    ///
1739
    /// # Errors
1740
    ///
1741
    /// This function may encounter any standard I/O error except `WouldBlock`.
1742
    ///
1743
    /// [`poll_peek_sender`]: method@Self::poll_peek_sender
1744
    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1745
0
    pub fn poll_peek_from(
1746
0
        &self,
1747
0
        cx: &mut Context<'_>,
1748
0
        buf: &mut ReadBuf<'_>,
1749
0
    ) -> Poll<io::Result<SocketAddr>> {
1750
        #[allow(clippy::blocks_in_conditions)]
1751
0
        let (n, addr) = ready!(self.io.registration().poll_read_io(cx, || {
1752
            // Safety: will not read the maybe uninitialized bytes.
1753
0
            let b = unsafe {
1754
0
                &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
1755
            };
1756
1757
0
            self.io.peek_from(b)
1758
0
        }))?;
1759
1760
        // Safety: We trust `recv` to have filled up `n` bytes in the buffer.
1761
0
        unsafe {
1762
0
            buf.assume_init(n);
1763
0
        }
1764
0
        buf.advance(n);
1765
0
        Poll::Ready(Ok(addr))
1766
0
    }
1767
1768
    /// Tries to receive data on the socket without removing it from the input queue.
1769
    /// On success, returns the number of bytes read and the sending address of the
1770
    /// datagram.
1771
    ///
1772
    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1773
    /// returned. This function is usually paired with `readable()`.
1774
    ///
1775
    /// # Notes
1776
    ///
1777
    /// On Windows, if the data is larger than the buffer specified, the buffer
1778
    /// is filled with the first part of the data, and peek returns the error
1779
    /// `WSAEMSGSIZE(10040)`. The excess data is lost.
1780
    /// Make sure to always use a sufficiently large buffer to hold the
1781
    /// maximum UDP packet size, which can be up to 65536 bytes in size.
1782
    ///
1783
    /// MacOS will return an error if you pass a zero-sized buffer.
1784
    ///
1785
    /// If you're merely interested in learning the sender of the data at the head of the queue,
1786
    /// try [`try_peek_sender`].
1787
    ///
1788
    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1789
    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1790
    /// Because UDP is stateless and does not validate the origin of a packet,
1791
    /// the attacker does not need to be able to intercept traffic in order to interfere.
1792
    /// It is important to be aware of this when designing your application-level protocol.
1793
    ///
1794
    /// [`try_peek_sender`]: method@Self::try_peek_sender
1795
    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1796
0
    pub fn try_peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1797
0
        self.io
1798
0
            .registration()
1799
0
            .try_io(Interest::READABLE, || self.io.peek_from(buf))
1800
0
    }
1801
1802
    /// Retrieve the sender of the data at the head of the input queue, waiting if empty.
1803
    ///
1804
    /// This is equivalent to calling [`peek_from`] with a zero-sized buffer,
1805
    /// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
1806
    ///
1807
    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1808
    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1809
    /// Because UDP is stateless and does not validate the origin of a packet,
1810
    /// the attacker does not need to be able to intercept traffic in order to interfere.
1811
    /// It is important to be aware of this when designing your application-level protocol.
1812
    ///
1813
    /// [`peek_from`]: method@Self::peek_from
1814
    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1815
0
    pub async fn peek_sender(&self) -> io::Result<SocketAddr> {
1816
0
        self.io
1817
0
            .registration()
1818
0
            .async_io(Interest::READABLE, || self.peek_sender_inner())
1819
0
            .await
1820
0
    }
1821
1822
    /// Retrieve the sender of the data at the head of the input queue,
1823
    /// scheduling a wakeup if empty.
1824
    ///
1825
    /// This is equivalent to calling [`poll_peek_from`] with a zero-sized buffer,
1826
    /// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
1827
    ///
1828
    /// # Notes
1829
    ///
1830
    /// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
1831
    /// `Waker` from the `Context` passed to the most recent call will be scheduled to
1832
    /// receive a wakeup.
1833
    ///
1834
    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1835
    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1836
    /// Because UDP is stateless and does not validate the origin of a packet,
1837
    /// the attacker does not need to be able to intercept traffic in order to interfere.
1838
    /// It is important to be aware of this when designing your application-level protocol.
1839
    ///
1840
    /// [`poll_peek_from`]: method@Self::poll_peek_from
1841
    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1842
0
    pub fn poll_peek_sender(&self, cx: &mut Context<'_>) -> Poll<io::Result<SocketAddr>> {
1843
0
        self.io
1844
0
            .registration()
1845
0
            .poll_read_io(cx, || self.peek_sender_inner())
1846
0
    }
1847
1848
    /// Try to retrieve the sender of the data at the head of the input queue.
1849
    ///
1850
    /// When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
1851
    /// returned. This function is usually paired with `readable()`.
1852
    ///
1853
    /// Note that the socket address **cannot** be implicitly trusted, because it is relatively
1854
    /// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
1855
    /// Because UDP is stateless and does not validate the origin of a packet,
1856
    /// the attacker does not need to be able to intercept traffic in order to interfere.
1857
    /// It is important to be aware of this when designing your application-level protocol.
1858
    ///
1859
    /// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
1860
0
    pub fn try_peek_sender(&self) -> io::Result<SocketAddr> {
1861
0
        self.io
1862
0
            .registration()
1863
0
            .try_io(Interest::READABLE, || self.peek_sender_inner())
1864
0
    }
1865
1866
    #[inline]
1867
0
    fn peek_sender_inner(&self) -> io::Result<SocketAddr> {
1868
0
        self.io.try_io(|| {
1869
0
            self.as_socket()
1870
0
                .peek_sender()?
1871
                // May be `None` if the platform doesn't populate the sender for some reason.
1872
                // In testing, that only occurred on macOS if you pass a zero-sized buffer,
1873
                // but the implementation of `Socket::peek_sender()` covers that.
1874
0
                .as_socket()
1875
0
                .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "sender not available"))
1876
0
        })
1877
0
    }
1878
1879
    /// Gets the value of the `SO_BROADCAST` option for this socket.
1880
    ///
1881
    /// For more information about this option, see [`set_broadcast`].
1882
    ///
1883
    /// [`set_broadcast`]: method@Self::set_broadcast
1884
0
    pub fn broadcast(&self) -> io::Result<bool> {
1885
0
        self.io.broadcast()
1886
0
    }
1887
1888
    /// Sets the value of the `SO_BROADCAST` option for this socket.
1889
    ///
1890
    /// When enabled, this socket is allowed to send packets to a broadcast
1891
    /// address.
1892
0
    pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
1893
0
        self.io.set_broadcast(on)
1894
0
    }
1895
1896
    /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
1897
    ///
1898
    /// For more information about this option, see [`set_multicast_loop_v4`].
1899
    ///
1900
    /// [`set_multicast_loop_v4`]: method@Self::set_multicast_loop_v4
1901
0
    pub fn multicast_loop_v4(&self) -> io::Result<bool> {
1902
0
        self.io.multicast_loop_v4()
1903
0
    }
1904
1905
    /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
1906
    ///
1907
    /// If enabled, multicast packets will be looped back to the local socket.
1908
    ///
1909
    /// # Note
1910
    ///
1911
    /// This may not have any effect on IPv6 sockets.
1912
0
    pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> {
1913
0
        self.io.set_multicast_loop_v4(on)
1914
0
    }
1915
1916
    /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
1917
    ///
1918
    /// For more information about this option, see [`set_multicast_ttl_v4`].
1919
    ///
1920
    /// [`set_multicast_ttl_v4`]: method@Self::set_multicast_ttl_v4
1921
0
    pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
1922
0
        self.io.multicast_ttl_v4()
1923
0
    }
1924
1925
    /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
1926
    ///
1927
    /// Indicates the time-to-live value of outgoing multicast packets for
1928
    /// this socket. The default value is 1 which means that multicast packets
1929
    /// don't leave the local network unless explicitly requested.
1930
    ///
1931
    /// # Note
1932
    ///
1933
    /// This may not have any effect on IPv6 sockets.
1934
0
    pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> {
1935
0
        self.io.set_multicast_ttl_v4(ttl)
1936
0
    }
1937
1938
    /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1939
    ///
1940
    /// For more information about this option, see [`set_multicast_loop_v6`].
1941
    ///
1942
    /// [`set_multicast_loop_v6`]: method@Self::set_multicast_loop_v6
1943
0
    pub fn multicast_loop_v6(&self) -> io::Result<bool> {
1944
0
        self.io.multicast_loop_v6()
1945
0
    }
1946
1947
    /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
1948
    ///
1949
    /// Controls whether this socket sees the multicast packets it sends itself.
1950
    ///
1951
    /// # Note
1952
    ///
1953
    /// This may not have any effect on IPv4 sockets.
1954
0
    pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> {
1955
0
        self.io.set_multicast_loop_v6(on)
1956
0
    }
1957
1958
    /// Gets the value of the `IPV6_TCLASS` option for this socket.
1959
    ///
1960
    /// For more information about this option, see [`set_tclass_v6`].
1961
    ///
1962
    /// [`set_tclass_v6`]: Self::set_tclass_v6
1963
    // https://docs.rs/socket2/0.6.1/src/socket2/sys/unix.rs.html#2541
1964
    #[cfg(any(
1965
        target_os = "android",
1966
        target_os = "dragonfly",
1967
        target_os = "freebsd",
1968
        target_os = "fuchsia",
1969
        target_os = "linux",
1970
        target_os = "macos",
1971
        target_os = "netbsd",
1972
        target_os = "openbsd",
1973
        target_os = "cygwin",
1974
    ))]
1975
    #[cfg_attr(
1976
        docsrs,
1977
        doc(cfg(any(
1978
            target_os = "android",
1979
            target_os = "dragonfly",
1980
            target_os = "freebsd",
1981
            target_os = "fuchsia",
1982
            target_os = "linux",
1983
            target_os = "macos",
1984
            target_os = "netbsd",
1985
            target_os = "openbsd",
1986
            target_os = "cygwin",
1987
        )))
1988
    )]
1989
0
    pub fn tclass_v6(&self) -> io::Result<u32> {
1990
0
        self.as_socket().tclass_v6()
1991
0
    }
1992
1993
    /// Sets the value for the `IPV6_TCLASS` option on this socket.
1994
    ///
1995
    /// Specifies the traffic class field that is used in every packet
1996
    /// sent from this socket.
1997
    ///
1998
    /// # Note
1999
    ///
2000
    /// This may not have any effect on IPv4 sockets.
2001
    // https://docs.rs/socket2/0.6.1/src/socket2/sys/unix.rs.html#2566
2002
    #[cfg(any(
2003
        target_os = "android",
2004
        target_os = "dragonfly",
2005
        target_os = "freebsd",
2006
        target_os = "fuchsia",
2007
        target_os = "linux",
2008
        target_os = "macos",
2009
        target_os = "netbsd",
2010
        target_os = "openbsd",
2011
        target_os = "cygwin",
2012
    ))]
2013
    #[cfg_attr(
2014
        docsrs,
2015
        doc(cfg(any(
2016
            target_os = "android",
2017
            target_os = "dragonfly",
2018
            target_os = "freebsd",
2019
            target_os = "fuchsia",
2020
            target_os = "linux",
2021
            target_os = "macos",
2022
            target_os = "netbsd",
2023
            target_os = "openbsd",
2024
            target_os = "cygwin",
2025
        )))
2026
    )]
2027
0
    pub fn set_tclass_v6(&self, tclass: u32) -> io::Result<()> {
2028
0
        self.as_socket().set_tclass_v6(tclass)
2029
0
    }
2030
2031
    /// Gets the value of the `IP_TTL` option for this socket.
2032
    ///
2033
    /// For more information about this option, see [`set_ttl`].
2034
    ///
2035
    /// [`set_ttl`]: method@Self::set_ttl
2036
    ///
2037
    /// # Examples
2038
    ///
2039
    /// ```no_run
2040
    /// use tokio::net::UdpSocket;
2041
    /// # use std::io;
2042
    ///
2043
    /// # async fn dox() -> io::Result<()> {
2044
    /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
2045
    ///
2046
    /// println!("{:?}", sock.ttl()?);
2047
    /// # Ok(())
2048
    /// # }
2049
    /// ```
2050
0
    pub fn ttl(&self) -> io::Result<u32> {
2051
0
        self.io.ttl()
2052
0
    }
2053
2054
    /// Sets the value for the `IP_TTL` option on this socket.
2055
    ///
2056
    /// This value sets the time-to-live field that is used in every packet sent
2057
    /// from this socket.
2058
    ///
2059
    /// # Examples
2060
    ///
2061
    /// ```no_run
2062
    /// use tokio::net::UdpSocket;
2063
    /// # use std::io;
2064
    ///
2065
    /// # async fn dox() -> io::Result<()> {
2066
    /// let sock = UdpSocket::bind("127.0.0.1:8080").await?;
2067
    /// sock.set_ttl(60)?;
2068
    ///
2069
    /// # Ok(())
2070
    /// # }
2071
    /// ```
2072
0
    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
2073
0
        self.io.set_ttl(ttl)
2074
0
    }
2075
2076
    /// Gets the value of the `IP_TOS` option for this socket.
2077
    ///
2078
    /// For more information about this option, see [`set_tos_v4`].
2079
    ///
2080
    /// [`set_tos_v4`]: Self::set_tos_v4
2081
    // https://docs.rs/socket2/0.6.1/src/socket2/socket.rs.html#1585
2082
    #[cfg(not(any(
2083
        target_os = "fuchsia",
2084
        target_os = "redox",
2085
        target_os = "solaris",
2086
        target_os = "illumos",
2087
        target_os = "haiku"
2088
    )))]
2089
    #[cfg_attr(
2090
        docsrs,
2091
        doc(cfg(not(any(
2092
            target_os = "fuchsia",
2093
            target_os = "redox",
2094
            target_os = "solaris",
2095
            target_os = "illumos",
2096
            target_os = "haiku"
2097
        ))))
2098
    )]
2099
0
    pub fn tos_v4(&self) -> io::Result<u32> {
2100
0
        self.as_socket().tos_v4()
2101
0
    }
2102
2103
    /// Deprecated. Use [`tos_v4()`] instead.
2104
    ///
2105
    /// [`tos_v4()`]: Self::tos_v4
2106
    #[deprecated(
2107
        note = "`tos` related methods have been renamed `tos_v4` since they are IPv4-specific."
2108
    )]
2109
    #[doc(hidden)]
2110
    #[cfg(not(any(
2111
        target_os = "fuchsia",
2112
        target_os = "redox",
2113
        target_os = "solaris",
2114
        target_os = "illumos",
2115
        target_os = "haiku"
2116
    )))]
2117
    #[cfg_attr(
2118
        docsrs,
2119
        doc(cfg(not(any(
2120
            target_os = "fuchsia",
2121
            target_os = "redox",
2122
            target_os = "solaris",
2123
            target_os = "illumos",
2124
            target_os = "haiku"
2125
        ))))
2126
    )]
2127
0
    pub fn tos(&self) -> io::Result<u32> {
2128
0
        self.tos_v4()
2129
0
    }
2130
2131
    /// Sets the value for the `IP_TOS` option on this socket.
2132
    ///
2133
    /// This value sets the type-of-service field that is used in every packet
2134
    /// sent from this socket.
2135
    ///
2136
    /// # Note
2137
    ///
2138
    /// - This may not have any effect on IPv6 sockets.
2139
    /// - On Windows, `IP_TOS` is only supported on [Windows 8+ or
2140
    ///   Windows Server 2012+.](https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options)
2141
    // https://docs.rs/socket2/0.6.1/src/socket2/socket.rs.html#1566
2142
    #[cfg(not(any(
2143
        target_os = "fuchsia",
2144
        target_os = "redox",
2145
        target_os = "solaris",
2146
        target_os = "illumos",
2147
        target_os = "haiku"
2148
    )))]
2149
    #[cfg_attr(
2150
        docsrs,
2151
        doc(cfg(not(any(
2152
            target_os = "fuchsia",
2153
            target_os = "redox",
2154
            target_os = "solaris",
2155
            target_os = "illumos",
2156
            target_os = "haiku"
2157
        ))))
2158
    )]
2159
0
    pub fn set_tos_v4(&self, tos: u32) -> io::Result<()> {
2160
0
        self.as_socket().set_tos_v4(tos)
2161
0
    }
2162
2163
    /// Deprecated. Use [`set_tos_v4()`] instead.
2164
    ///
2165
    /// [`set_tos_v4()`]: Self::set_tos_v4
2166
    #[deprecated(
2167
        note = "`tos` related methods have been renamed `tos_v4` since they are IPv4-specific."
2168
    )]
2169
    #[doc(hidden)]
2170
    #[cfg(not(any(
2171
        target_os = "fuchsia",
2172
        target_os = "redox",
2173
        target_os = "solaris",
2174
        target_os = "illumos",
2175
        target_os = "haiku"
2176
    )))]
2177
    #[cfg_attr(
2178
        docsrs,
2179
        doc(cfg(not(any(
2180
            target_os = "fuchsia",
2181
            target_os = "redox",
2182
            target_os = "solaris",
2183
            target_os = "illumos",
2184
            target_os = "haiku"
2185
        ))))
2186
    )]
2187
0
    pub fn set_tos(&self, tos: u32) -> io::Result<()> {
2188
0
        self.set_tos_v4(tos)
2189
0
    }
2190
2191
    /// Gets the value for the `SO_BINDTODEVICE` option on this socket
2192
    ///
2193
    /// This value gets the socket-bound device's interface name.
2194
    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux",))]
2195
    #[cfg_attr(
2196
        docsrs,
2197
        doc(cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux",)))
2198
    )]
2199
0
    pub fn device(&self) -> io::Result<Option<Vec<u8>>> {
2200
0
        self.as_socket().device()
2201
0
    }
2202
2203
    /// Sets the value for the `SO_BINDTODEVICE` option on this socket
2204
    ///
2205
    /// If a socket is bound to an interface, only packets received from that
2206
    /// particular interface are processed by the socket. Note that this only
2207
    /// works for some socket types, particularly `AF_INET` sockets.
2208
    ///
2209
    /// If `interface` is `None` or an empty string it removes the binding.
2210
    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
2211
    #[cfg_attr(
2212
        docsrs,
2213
        doc(cfg(all(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))))
2214
    )]
2215
0
    pub fn bind_device(&self, interface: Option<&[u8]>) -> io::Result<()> {
2216
0
        self.as_socket().bind_device(interface)
2217
0
    }
2218
2219
    /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
2220
    ///
2221
    /// This function specifies a new multicast group for this socket to join.
2222
    /// The address must be a valid multicast address, and `interface` is the
2223
    /// address of the local interface with which the system should join the
2224
    /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
2225
    /// interface is chosen by the system.
2226
0
    pub fn join_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
2227
0
        self.io.join_multicast_v4(&multiaddr, &interface)
2228
0
    }
2229
2230
    /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
2231
    ///
2232
    /// This function specifies a new multicast group for this socket to join.
2233
    /// The address must be a valid multicast address, and `interface` is the
2234
    /// index of the interface to join/leave (or 0 to indicate any interface).
2235
0
    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
2236
0
        self.io.join_multicast_v6(multiaddr, interface)
2237
0
    }
2238
2239
    /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
2240
    ///
2241
    /// For more information about this option, see [`join_multicast_v4`].
2242
    ///
2243
    /// [`join_multicast_v4`]: method@Self::join_multicast_v4
2244
0
    pub fn leave_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> {
2245
0
        self.io.leave_multicast_v4(&multiaddr, &interface)
2246
0
    }
2247
2248
    /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
2249
    ///
2250
    /// For more information about this option, see [`join_multicast_v6`].
2251
    ///
2252
    /// [`join_multicast_v6`]: method@Self::join_multicast_v6
2253
0
    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
2254
0
        self.io.leave_multicast_v6(multiaddr, interface)
2255
0
    }
2256
2257
    /// Returns the value of the `SO_ERROR` option.
2258
    ///
2259
    /// # Examples
2260
    /// ```
2261
    /// use tokio::net::UdpSocket;
2262
    /// use std::io;
2263
    ///
2264
    /// #[tokio::main]
2265
    /// async fn main() -> io::Result<()> {
2266
    /// #   if cfg!(miri) { return Ok(()); } // No `socket` in miri.
2267
    ///     // Create a socket
2268
    ///     let socket = UdpSocket::bind("0.0.0.0:8080").await?;
2269
    ///
2270
    ///     if let Ok(Some(err)) = socket.take_error() {
2271
    ///         println!("Got error: {:?}", err);
2272
    ///     }
2273
    ///
2274
    ///     Ok(())
2275
    /// }
2276
    /// ```
2277
0
    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
2278
0
        self.io.take_error()
2279
0
    }
2280
}
2281
2282
impl TryFrom<std::net::UdpSocket> for UdpSocket {
2283
    type Error = io::Error;
2284
2285
    /// Consumes stream, returning the tokio I/O object.
2286
    ///
2287
    /// This is equivalent to
2288
    /// [`UdpSocket::from_std(stream)`](UdpSocket::from_std).
2289
0
    fn try_from(stream: std::net::UdpSocket) -> Result<Self, Self::Error> {
2290
0
        Self::from_std(stream)
2291
0
    }
2292
}
2293
2294
impl fmt::Debug for UdpSocket {
2295
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2296
0
        self.io.fmt(f)
2297
0
    }
2298
}
2299
2300
#[cfg(unix)]
2301
mod sys {
2302
    use super::UdpSocket;
2303
    use std::os::unix::prelude::*;
2304
2305
    impl AsRawFd for UdpSocket {
2306
0
        fn as_raw_fd(&self) -> RawFd {
2307
0
            self.io.as_raw_fd()
2308
0
        }
2309
    }
2310
2311
    impl AsFd for UdpSocket {
2312
0
        fn as_fd(&self) -> BorrowedFd<'_> {
2313
0
            unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
2314
0
        }
2315
    }
2316
}
2317
2318
cfg_windows! {
2319
    use crate::os::windows::io::{AsRawSocket, RawSocket};
2320
    use crate::os::windows::io::{AsSocket, BorrowedSocket};
2321
2322
    impl AsRawSocket for UdpSocket {
2323
        fn as_raw_socket(&self) -> RawSocket {
2324
            self.io.as_raw_socket()
2325
        }
2326
    }
2327
2328
    impl AsSocket for UdpSocket {
2329
        fn as_socket(&self) -> BorrowedSocket<'_> {
2330
            unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
2331
        }
2332
    }
2333
}