• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 use std::fmt::{Debug, Formatter};
15 use std::io;
16 use std::mem::MaybeUninit;
17 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
18 use std::task::{Context, Poll};
19 
20 use ylong_io::Interest;
21 
22 use crate::io::ReadBuf;
23 use crate::net::sys::ToSocketAddrs;
24 use crate::net::AsyncSource;
25 
26 /// Asynchronous UdpSocket.
27 ///
28 /// # Examples
29 ///
30 /// ```rust
31 /// use std::io;
32 ///
33 /// use ylong_runtime::net::UdpSocket;
34 ///
35 /// async fn io_func() -> io::Result<()> {
36 ///     let sender_addr = "127.0.0.1:8081";
37 ///     let receiver_addr = "127.0.0.1:8082";
38 ///     let mut sender = UdpSocket::bind(sender_addr).await?;
39 ///     let mut receiver = UdpSocket::bind(sender_addr).await?;
40 ///
41 ///     let len = sender.send_to(b"Hello", receiver_addr).await?;
42 ///     println!("{:?} bytes sent", len);
43 ///
44 ///     let mut buf = [0; 1024];
45 ///     let (len, addr) = receiver.recv_from(&mut buf).await?;
46 ///     println!("{:?} bytes received from {:?}", len, addr);
47 ///
48 ///     let connected_sender = match sender.connect(receiver_addr).await {
49 ///         Ok(socket) => socket,
50 ///         Err(e) => {
51 ///             return Err(e);
52 ///         }
53 ///     };
54 ///     let connected_receiver = match receiver.connect(sender_addr).await {
55 ///         Ok(socket) => socket,
56 ///         Err(e) => {
57 ///             return Err(e);
58 ///         }
59 ///     };
60 ///     let len = connected_sender.send(b"Hello").await?;
61 ///     println!("{:?} bytes sent", len);
62 ///     let len = connected_receiver.recv(&mut buf).await?;
63 ///     println!("{:?} bytes received from {:?}", len, sender_addr);
64 ///     Ok(())
65 /// }
66 /// ```
67 pub struct UdpSocket {
68     pub(crate) source: AsyncSource<ylong_io::UdpSocket>,
69 }
70 
71 /// A connected asynchronous UdpSocket.
72 pub struct ConnectedUdpSocket {
73     pub(crate) source: AsyncSource<ylong_io::ConnectedUdpSocket>,
74 }
75 
76 impl Debug for UdpSocket {
fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result77     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
78         self.source.fmt(f)
79     }
80 }
81 
82 impl Debug for ConnectedUdpSocket {
fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result83     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
84         self.source.fmt(f)
85     }
86 }
87 
88 impl UdpSocket {
89     /// Creates a new UDP socket and attempts to bind it to the address provided
90     ///
91     /// # Note
92     ///
93     /// If there are multiple addresses in SocketAddr, it will attempt to
94     /// connect them in sequence until one of the addrs returns success. If
95     /// all connections fail, it returns the error of the last connection.
96     /// This behavior is consistent with std.
97     ///
98     /// # Panic
99     /// Calling this method outside of a Ylong Runtime could cause panic.
100     ///
101     /// # Examples
102     ///
103     /// ```rust
104     /// use std::io;
105     ///
106     /// use ylong_runtime::net::UdpSocket;
107     ///
108     /// async fn io_func() -> io::Result<()> {
109     ///     let addr = "127.0.0.1:8080";
110     ///     let mut sock = UdpSocket::bind(addr).await?;
111     ///     Ok(())
112     /// }
113     /// ```
bind<A: ToSocketAddrs>(addr: A) -> io::Result<Self>114     pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<Self> {
115         super::addr::each_addr(addr, ylong_io::UdpSocket::bind)
116             .await
117             .map(UdpSocket::new)
118             .and_then(|op| op)
119     }
120 
121     /// Internal interfaces.
122     /// Creates new ylong_runtime::net::UdpSocket according to the incoming
123     /// ylong_io::UdpSocket.
new(socket: ylong_io::UdpSocket) -> io::Result<Self>124     pub(crate) fn new(socket: ylong_io::UdpSocket) -> io::Result<Self> {
125         let source = AsyncSource::new(socket, None)?;
126         Ok(UdpSocket { source })
127     }
128 
129     /// Sets the default address for the UdpSocket and limits packets to
130     /// those that are read via recv from the specific address.
131     ///
132     /// Returns the connected UdpSocket if succeeds.
133     ///
134     /// # Note
135     ///
136     /// If there are multiple addresses in SocketAddr, it will attempt to
137     /// connect them in sequence until one of the addrs returns success. If
138     /// all connections fail, it returns the error of the last connection.
139     /// This behavior is consistent with std.
140     ///
141     /// # Panic
142     /// Calling this method outside of a Ylong Runtime could cause panic.
143     ///
144     /// # Examples
145     ///
146     /// ```rust
147     /// use std::io;
148     ///
149     /// use ylong_runtime::net::UdpSocket;
150     ///
151     /// async fn io_func() -> io::Result<()> {
152     ///     let local_addr = "127.0.0.1:8080";
153     ///     let sock = UdpSocket::bind(local_addr).await?;
154     ///     let remote_addr = "127.0.0.1:8081";
155     ///     let connected_sock = match sock.connect(remote_addr).await {
156     ///         Ok(socket) => socket,
157     ///         Err(e) => {
158     ///             return Err(e);
159     ///         }
160     ///     };
161     ///     Ok(())
162     /// }
163     /// ```
connect<A: ToSocketAddrs>(self, addr: A) -> io::Result<ConnectedUdpSocket>164     pub async fn connect<A: ToSocketAddrs>(self, addr: A) -> io::Result<ConnectedUdpSocket> {
165         let local_addr = self.local_addr()?;
166         drop(self);
167 
168         let addrs = addr.to_socket_addrs().await?;
169 
170         let mut last_e = None;
171 
172         for addr in addrs {
173             let socket = ylong_io::UdpSocket::bind(local_addr)?;
174             match socket.connect(addr) {
175                 Ok(socket) => return ConnectedUdpSocket::new(socket),
176                 Err(e) => last_e = Some(e),
177             }
178         }
179 
180         Err(last_e.unwrap_or(io::Error::new(
181             io::ErrorKind::InvalidInput,
182             "addr could not resolve to any address",
183         )))
184     }
185 
186     /// Returns the local address that this socket is bound to.
187     ///
188     /// # Examples
189     ///
190     /// ```rust
191     /// use std::io;
192     ///
193     /// use ylong_runtime::net::UdpSocket;
194     ///
195     /// async fn io_func() -> io::Result<()> {
196     ///     let addr = "127.0.0.1:8080";
197     ///     let mut sock = UdpSocket::bind(addr).await?;
198     ///     let local_addr = sock.local_addr()?;
199     ///     Ok(())
200     /// }
201     /// ```
local_addr(&self) -> io::Result<SocketAddr>202     pub fn local_addr(&self) -> io::Result<SocketAddr> {
203         self.source.local_addr()
204     }
205 
206     /// Sends data on the socket to the given address. On success, returns the
207     /// number of bytes written. This will return an error when the IP
208     /// version of the local socket does not match that returned from
209     /// SocketAddr.
210     ///
211     /// # Return value
212     /// The function returns:
213     /// * `Ok(n)` n is the number of bytes sent.
214     /// * `Err(e)` if an error is encountered.
215     ///
216     /// # Examples
217     ///
218     /// ```rust
219     /// use std::io;
220     ///
221     /// use ylong_runtime::net::UdpSocket;
222     ///
223     /// async fn io_func() -> io::Result<()> {
224     ///     let local_addr = "127.0.0.1:8080";
225     ///     let sock = UdpSocket::bind(local_addr).await?;
226     ///     let remote_addr = "127.0.0.1:8081";
227     ///     let len = sock.send_to(b"hello world", remote_addr).await?;
228     ///     println!("Sent {} bytes", len);
229     ///     Ok(())
230     /// }
231     /// ```
send_to<A: ToSocketAddrs>(&self, buf: &[u8], target: A) -> io::Result<usize>232     pub async fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], target: A) -> io::Result<usize> {
233         match target.to_socket_addrs().await?.next() {
234             Some(addr) => {
235                 self.source
236                     .async_process(Interest::WRITABLE, || self.source.send_to(buf, addr))
237                     .await
238             }
239             None => Err(io::Error::new(
240                 io::ErrorKind::InvalidInput,
241                 "addr could not resolve to address",
242             )),
243         }
244     }
245 
246     /// Attempts to send data on the socket to the given address.
247     ///
248     /// The function is usually paired with `writable`.
249     ///
250     /// # Return value
251     /// The function returns:
252     /// * `Ok(n)` n is the number of bytes sent.
253     /// * `Err(e)` if an error is encountered.
254     /// When the remote cannot receive the message, an
255     /// [`io::ErrorKind::WouldBlock`] will be returned. This will return an
256     /// error If the IP version of the local socket does not match that
257     /// returned from SocketAddr.
258     ///
259     /// # Examples
260     ///
261     /// ```rust
262     /// use std::io;
263     ///
264     /// use ylong_runtime::net::UdpSocket;
265     ///
266     /// async fn io_func() -> io::Result<()> {
267     ///     let local_addr = "127.0.0.1:8080";
268     ///     let sock = UdpSocket::bind(local_addr).await?;
269     ///     let remote_addr = "127.0.0.1:8081".parse().unwrap();
270     ///     let len = sock.try_send_to(b"hello world", remote_addr)?;
271     ///     Ok(())
272     /// }
273     /// ```
try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize>274     pub fn try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
275         self.source
276             .try_io(Interest::WRITABLE, || self.source.send_to(buf, target))
277     }
278 
279     /// Attempts to send data on the socket to a given address.
280     /// Note that on multiple calls to a poll_* method in the send direction,
281     /// only the Waker from the Context passed to the most recent call will be
282     /// scheduled to receive a wakeup
283     ///
284     /// # Return value
285     /// The function returns:
286     /// * `Poll::Pending` if the socket is not ready to write
287     /// * `Poll::Ready(Ok(n))` n is the number of bytes sent.
288     /// * `Poll::Ready(Err(e))` if an error is encountered.
289     ///
290     /// # Examples
291     ///
292     /// ```rust
293     /// use std::io;
294     ///
295     /// use ylong_runtime::futures::poll_fn;
296     /// use ylong_runtime::net::UdpSocket;
297     ///
298     /// async fn io_func() -> io::Result<()> {
299     ///     let local_addr = "127.0.0.1:8080";
300     ///     let sock = UdpSocket::bind(local_addr).await?;
301     ///     let remote_addr = "127.0.0.1:8081".parse().unwrap();
302     ///     let len = poll_fn(|cx| sock.poll_send_to(cx, b"Hello", remote_addr)).await?;
303     ///     println!("Sent {} bytes", len);
304     ///     Ok(())
305     /// }
306     /// ```
poll_send_to( &self, cx: &mut Context<'_>, buf: &[u8], target: SocketAddr, ) -> Poll<io::Result<usize>>307     pub fn poll_send_to(
308         &self,
309         cx: &mut Context<'_>,
310         buf: &[u8],
311         target: SocketAddr,
312     ) -> Poll<io::Result<usize>> {
313         self.source
314             .poll_write_io(cx, || self.source.send_to(buf, target))
315     }
316 
317     /// Receives a single datagram message on the socket. On success, returns
318     /// the number of bytes read and the origin. The function must be called
319     /// with valid byte array buf of sufficient size to hold the message
320     /// bytes. If a message is too long to fit in the supplied buffer,
321     /// excess bytes may be discarded.
322     ///
323     /// # Return value
324     /// The function returns:
325     /// * `Ok((n, addr))` n is the number of bytes received, addr is the address
326     ///   of sender.
327     /// * `Err(e)` if an error is encountered.
328     ///
329     /// # Examples
330     ///
331     /// ```rust
332     /// use std::io;
333     ///
334     /// use ylong_runtime::net::UdpSocket;
335     ///
336     /// async fn io_func() -> io::Result<()> {
337     ///     let local_addr = "127.0.0.1:8080";
338     ///     let sock = UdpSocket::bind(local_addr).await?;
339     ///     let mut recv_buf = [0_u8; 12];
340     ///     let (len, addr) = sock.recv_from(&mut recv_buf).await?;
341     ///     println!("received {:?} bytes from {:?}", len, addr);
342     ///     Ok(())
343     /// }
344     /// ```
recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)>345     pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
346         self.source
347             .async_process(Interest::READABLE, || self.source.recv_from(buf))
348             .await
349     }
350 
351     /// Attempts to receive a single datagram message on the socket.
352     ///
353     /// The function is usually paired with `readable` and must be called with
354     /// valid byte array buf of sufficient size to hold the message bytes.
355     /// If a message is too long to fit in the supplied buffer, excess bytes
356     /// may be discarded.
357     ///
358     /// # Return value
359     /// The function returns:
360     /// * `Ok(n, addr)` n is the number of bytes received, addr is the address
361     ///   of the remote.
362     /// * `Err(e)` if an error is encountered.
363     /// If there is no pending data, an [`io::ErrorKind::WouldBlock`] will be
364     /// returned.
365     ///
366     /// # Examples
367     ///
368     /// ```rust
369     /// use std::io;
370     ///
371     /// use ylong_runtime::net::UdpSocket;
372     ///
373     /// async fn io_func() -> io::Result<()> {
374     ///     let local_addr = "127.0.0.1:8080";
375     ///     let sock = UdpSocket::bind(local_addr).await?;
376     ///     let mut recv_buf = [0_u8; 12];
377     ///     let (len, addr) = sock.try_recv_from(&mut recv_buf)?;
378     ///     Ok(())
379     /// }
380     /// ```
try_recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)>381     pub fn try_recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
382         self.source
383             .try_io(Interest::READABLE, || self.source.recv_from(buf))
384     }
385 
386     /// Attempts to receives single datagram on the socket from the remote
387     /// address to which it is connected, without removing the message from
388     /// input queue. On success, returns the number of bytes peeked.
389     ///
390     /// # Examples
391     ///
392     /// ```rust
393     /// use std::io;
394     ///
395     /// use ylong_runtime::net::UdpSocket;
396     ///
397     /// async fn io_func() -> io::Result<()> {
398     ///     let local_addr = "127.0.0.1:8080";
399     ///     let sock = UdpSocket::bind(local_addr).await?;
400     ///     let mut buf = [0; 10];
401     ///     let (number_of_bytes, src_addr) =
402     ///         sock.peek_from(&mut buf).await.expect("Didn't receive data");
403     ///     let filled_buf = &mut buf[..number_of_bytes];
404     ///     Ok(())
405     /// }
406     /// ```
peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)>407     pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
408         self.source
409             .async_process(Interest::READABLE, || self.source.peek_from(buf))
410             .await
411     }
412 
413     /// Attempts to Receives single datagram on the socket from the remote
414     /// address to which it is connected, without removing the message from
415     /// input queue. On success, returns the number of bytes peeked.
416     ///
417     /// # Examples
418     ///
419     /// ```rust
420     /// use std::io;
421     ///
422     /// use ylong_runtime::net::UdpSocket;
423     ///
424     /// async fn io_func() -> io::Result<()> {
425     ///     let local_addr = "127.0.0.1:8080";
426     ///     let sock = UdpSocket::bind(local_addr).await?;
427     ///     let mut buf = [0; 10];
428     ///     let (number_of_bytes, src_addr) =
429     ///         sock.try_peek_from(&mut buf).expect("Didn't receive data");
430     ///     Ok(())
431     /// }
432     /// ```
try_peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)>433     pub fn try_peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
434         self.source
435             .try_io(Interest::READABLE, || self.source.peek_from(buf))
436     }
437 
438     /// Attempts to receives single datagram on the socket from the remote
439     /// address to which it is connected, without removing the message from
440     /// input queue. On success, returns the number of bytes peeked.
441     ///
442     /// # Return value
443     /// The function returns:
444     /// * `Poll::Pending` if the socket is not ready to read
445     /// * `Poll::Ready(Ok(addr))` reads data from addr into ReadBuf if the
446     ///   socket is ready
447     /// * `Poll::Ready(Err(e))` if an error is encountered.
448     ///
449     /// # Examples
450     ///
451     /// ```rust
452     /// use std::io;
453     ///
454     /// use ylong_runtime::futures::poll_fn;
455     /// use ylong_runtime::io::ReadBuf;
456     /// use ylong_runtime::net::UdpSocket;
457     ///
458     /// async fn io_func() -> io::Result<()> {
459     ///     let local_addr = "127.0.0.1:8080";
460     ///     let sock = UdpSocket::bind(local_addr).await?;
461     ///     let mut recv_buf = [0_u8; 12];
462     ///     let mut read = ReadBuf::new(&mut recv_buf);
463     ///     let addr = poll_fn(|cx| sock.poll_peek_from(cx, &mut read)).await?;
464     ///     println!("received {:?} from {:?}", read.filled(), addr);
465     ///     Ok(())
466     /// }
467     /// ```
poll_peek_from( &self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<SocketAddr>>468     pub fn poll_peek_from(
469         &self,
470         cx: &mut Context<'_>,
471         buf: &mut ReadBuf<'_>,
472     ) -> Poll<io::Result<SocketAddr>> {
473         let ret = self.source.poll_read_io(cx, || unsafe {
474             let slice = &mut *(buf.unfilled_mut() as *mut [MaybeUninit<u8>] as *mut [u8]);
475             self.source.peek_from(slice)
476         });
477         let (r_len, r_addr) = match ret {
478             Poll::Ready(Ok(x)) => x,
479             Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
480             Poll::Pending => return Poll::Pending,
481         };
482         buf.assume_init(r_len);
483         buf.advance(r_len);
484 
485         Poll::Ready(Ok(r_addr))
486     }
487 
488     /// Waits for the socket to become readable.
489     ///
490     /// This function is usually paired up with [`UdpSocket::try_recv_from`]
491     ///
492     /// # Examples
493     ///
494     /// ```
495     /// use std::io;
496     ///
497     /// use ylong_runtime::net::UdpSocket;
498     ///
499     /// async fn io_func() -> io::Result<()> {
500     ///     let local_addr = "127.0.0.1:8080";
501     ///     let sock = UdpSocket::bind(local_addr).await?;
502     ///     sock.readable().await?;
503     ///     let mut buf = [0; 12];
504     ///     let (len, addr) = sock.try_recv_from(&mut buf)?;
505     ///     Ok(())
506     /// }
507     /// ```
readable(&self) -> io::Result<()>508     pub async fn readable(&self) -> io::Result<()> {
509         self.source.entry.readiness(Interest::READABLE).await?;
510         Ok(())
511     }
512 
513     /// Waits for the socket to become writable.
514     ///
515     /// This function is usually paired up with [`UdpSocket::try_send_to`]
516     ///
517     /// # Examples
518     /// ```
519     /// use std::io;
520     ///
521     /// use ylong_runtime::net::UdpSocket;
522     ///
523     /// async fn io_func() -> io::Result<()> {
524     ///     let local_addr = "127.0.0.1:8080";
525     ///     let remote_addr = "127.0.0.1:8080".parse().unwrap();
526     ///     let sock = UdpSocket::bind(local_addr).await?;
527     ///     sock.writable().await?;
528     ///     let len = sock.try_send_to(b"hello", remote_addr)?;
529     ///     Ok(())
530     /// }
531     /// ```
writable(&self) -> io::Result<()>532     pub async fn writable(&self) -> io::Result<()> {
533         self.source.entry.readiness(Interest::WRITABLE).await?;
534         Ok(())
535     }
536 
537     /// Attempts to receive a single datagram on the socket.
538     /// Note that on multiple calls to a poll_* method in the recv direction,
539     /// only the Waker from the Context passed to the most recent call will be
540     /// scheduled to receive a wakeup.
541     ///
542     /// # Return value
543     /// The function returns:
544     /// * `Poll::Pending` if the socket is not ready to read
545     /// * `Poll::Ready(Ok(addr))` reads data from addr into ReadBuf if the
546     ///   socket is ready
547     /// * `Poll::Ready(Err(e))` if an error is encountered.
548     ///
549     /// # Examples
550     ///
551     /// ```rust
552     /// use std::io;
553     ///
554     /// use ylong_runtime::futures::poll_fn;
555     /// use ylong_runtime::io::ReadBuf;
556     /// use ylong_runtime::net::UdpSocket;
557     ///
558     /// async fn io_func() -> io::Result<()> {
559     ///     let local_addr = "127.0.0.1:8080";
560     ///     let sock = UdpSocket::bind(local_addr).await?;
561     ///     let mut recv_buf = [0_u8; 12];
562     ///     let mut read = ReadBuf::new(&mut recv_buf);
563     ///     let addr = poll_fn(|cx| sock.poll_recv_from(cx, &mut read)).await?;
564     ///     println!("received {:?} from {:?}", read.filled(), addr);
565     ///     Ok(())
566     /// }
567     /// ```
poll_recv_from( &self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<SocketAddr>>568     pub fn poll_recv_from(
569         &self,
570         cx: &mut Context<'_>,
571         buf: &mut ReadBuf<'_>,
572     ) -> Poll<io::Result<SocketAddr>> {
573         let ret = self.source.poll_read_io(cx, || unsafe {
574             let slice = &mut *(buf.unfilled_mut() as *mut [MaybeUninit<u8>] as *mut [u8]);
575             self.source.recv_from(slice)
576         });
577         let (r_len, r_addr) = match ret {
578             Poll::Ready(Ok(x)) => x,
579             Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
580             Poll::Pending => return Poll::Pending,
581         };
582         buf.assume_init(r_len);
583         buf.advance(r_len);
584 
585         Poll::Ready(Ok(r_addr))
586     }
587 
588     /// Sets the value of the `SO_BROADCAST` option for this socket.
589     /// When enabled, this socket is allowed to send packets to a broadcast
590     /// address.
591     ///
592     /// # Examples
593     ///
594     /// ```rust
595     /// use std::io;
596     ///
597     /// use ylong_runtime::net::UdpSocket;
598     ///
599     /// async fn io_func() -> io::Result<()> {
600     ///     let local_addr = "127.0.0.1:8080";
601     ///     let broadcast_socket = UdpSocket::bind(local_addr).await?;
602     ///     if broadcast_socket.broadcast()? == false {
603     ///         broadcast_socket.set_broadcast(true)?;
604     ///     }
605     ///     assert_eq!(broadcast_socket.broadcast()?, true);
606     ///     Ok(())
607     /// }
608     /// ```
set_broadcast(&self, on: bool) -> io::Result<()>609     pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
610         self.source.set_broadcast(on)
611     }
612 
613     /// Gets the value of the `SO_BROADCAST` option for this socket.
614     ///
615     /// # Examples
616     ///
617     /// ```rust
618     /// use std::io;
619     ///
620     /// use ylong_runtime::net::UdpSocket;
621     ///
622     /// async fn io_func() -> io::Result<()> {
623     ///     let local_addr = "127.0.0.1:8080";
624     ///     let broadcast_socket = UdpSocket::bind(local_addr).await?;
625     ///     assert_eq!(broadcast_socket.broadcast()?, false);
626     ///     Ok(())
627     /// }
628     /// ```
broadcast(&self) -> io::Result<bool>629     pub fn broadcast(&self) -> io::Result<bool> {
630         self.source.broadcast()
631     }
632 
633     /// Sets the value for the IP_TTL option on this socket.
634     ///
635     /// # Examples
636     ///
637     /// ```no_run
638     /// use std::io;
639     ///
640     /// use ylong_runtime::net::UdpSocket;
641     ///
642     /// async fn io_func() -> io::Result<()> {
643     ///     let local_addr = "127.0.0.1:8080";
644     ///     let socket = UdpSocket::bind(local_addr).await?;
645     ///     socket.set_ttl(100).expect("set_ttl call failed");
646     ///     Ok(())
647     /// }
648     /// ```
set_ttl(&self, ttl: u32) -> io::Result<()>649     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
650         self.source.set_ttl(ttl)
651     }
652 
653     /// Sets the value for the IP_TTL option on this socket.
654     ///
655     /// # Examples
656     ///
657     /// ```no_run
658     /// use std::io;
659     ///
660     /// use ylong_runtime::net::UdpSocket;
661     ///
662     /// async fn io_func() -> io::Result<()> {
663     ///     let local_addr = "127.0.0.1:8080";
664     ///     let socket = UdpSocket::bind(local_addr).await?;
665     ///     socket.set_ttl(100).expect("set_ttl call failed");
666     ///     assert_eq!(socket.ttl().unwrap(), 100);
667     ///     Ok(())
668     /// }
669     /// ```
ttl(&self) -> io::Result<u32>670     pub fn ttl(&self) -> io::Result<u32> {
671         self.source.ttl()
672     }
673 
674     /// Gets the value of the SO_ERROR option on this socket.
675     ///
676     /// # Examples
677     ///
678     /// ```no_run
679     /// use std::io;
680     ///
681     /// use ylong_runtime::net::UdpSocket;
682     ///
683     /// async fn io_func() -> io::Result<()> {
684     ///     let addr = "127.0.0.1:34254";
685     ///     let socket = UdpSocket::bind(addr)
686     ///         .await
687     ///         .expect("couldn't bind to address");
688     ///     match socket.take_error() {
689     ///         Ok(Some(error)) => println!("UdpSocket error: {error:?}"),
690     ///         Ok(None) => println!("No error"),
691     ///         Err(error) => println!("UdpSocket.take_error failed: {error:?}"),
692     ///     }
693     ///     Ok(())
694     /// }
695     /// ```
take_error(&self) -> io::Result<Option<io::Error>>696     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
697         self.source.take_error()
698     }
699 
700     /// Gets the value of the IP_MULTICAST_LOOP option for this socket.
multicast_loop_v4(&self) -> io::Result<bool>701     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
702         self.source.multicast_loop_v4()
703     }
704 
705     /// Sets the value of the IP_MULTICAST_LOOP option for this socket.
706     /// If enabled, multicast packets will be looped back to the local socket.
707     /// Note that this might not have any effect on IPv6 sockets.
set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()>708     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
709         self.source.set_multicast_loop_v4(multicast_loop_v4)
710     }
711 
712     /// Gets the value of the IP_MULTICAST_TTL option for this socket.
multicast_ttl_v4(&self) -> io::Result<u32>713     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
714         self.source.multicast_ttl_v4()
715     }
716 
717     /// Sets the value of the IP_MULTICAST_TTL option for this socket.
718     /// Indicates the time-to-live value of outgoing multicast packets for this
719     /// socket. The default value is 1 which means that multicast packets don't
720     /// leave the local network unless explicitly requested. Note that this
721     /// might not have any effect on IPv6 sockets.
set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()>722     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
723         self.source.set_multicast_ttl_v4(multicast_ttl_v4)
724     }
725 
726     /// Gets the value of the IPV6_MULTICAST_LOOP option for this socket.
multicast_loop_v6(&self) -> io::Result<bool>727     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
728         self.source.multicast_loop_v6()
729     }
730 
731     /// Sets the value of the IPV6_MULTICAST_LOOP option for this socket.
732     /// Controls whether this socket sees the multicast packets it sends itself.
733     /// Note that this might not have any affect on IPv4 sockets.
set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()>734     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
735         self.source.set_multicast_loop_v6(multicast_loop_v6)
736     }
737 
738     /// Executes an operation of the IP_ADD_MEMBERSHIP type.
join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>739     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
740         self.source.join_multicast_v4(multiaddr, interface)
741     }
742 
743     /// Executes an operation of the IPV6_ADD_MEMBERSHIP type.
join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>744     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
745         self.source.join_multicast_v6(multiaddr, interface)
746     }
747 
748     /// Executes an operation of the IP_DROP_MEMBERSHIP type.
leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>749     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
750         self.source.leave_multicast_v4(multiaddr, interface)
751     }
752 
753     /// Executes an operation of the IPV6_DROP_MEMBERSHIP type.
leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>754     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
755         self.source.leave_multicast_v6(multiaddr, interface)
756     }
757 }
758 
759 impl ConnectedUdpSocket {
760     /// Internal interfaces.
761     /// Creates new ylong_runtime::net::ConnectedUdpSocket according to the
762     /// incoming ylong_io::UdpSocket.
new(socket: ylong_io::ConnectedUdpSocket) -> io::Result<Self>763     pub(crate) fn new(socket: ylong_io::ConnectedUdpSocket) -> io::Result<Self> {
764         let source = AsyncSource::new(socket, None)?;
765         Ok(ConnectedUdpSocket { source })
766     }
767 
768     /// Returns the local address that this socket is bound to.
769     ///
770     /// # Examples
771     ///
772     /// ```rust
773     /// use std::io;
774     ///
775     /// use ylong_runtime::net::UdpSocket;
776     ///
777     /// async fn io_func() -> io::Result<()> {
778     ///     let addr = "127.0.0.1:8080";
779     ///     let mut sock = UdpSocket::bind(addr).await?;
780     ///     let remote_addr = "127.0.0.1:8081";
781     ///     let connected_sock = match sock.connect(remote_addr).await {
782     ///         Ok(socket) => socket,
783     ///         Err(e) => {
784     ///             return Err(e);
785     ///         }
786     ///     };
787     ///     let local_addr = connected_sock.local_addr()?;
788     ///     Ok(())
789     /// }
790     /// ```
local_addr(&self) -> io::Result<SocketAddr>791     pub fn local_addr(&self) -> io::Result<SocketAddr> {
792         self.source.local_addr()
793     }
794 
795     /// Returns the socket address of the remote peer this socket was connected
796     /// to.
797     ///
798     /// # Examples
799     ///
800     /// ```rust
801     /// use std::io;
802     ///
803     /// use ylong_runtime::net::UdpSocket;
804     ///
805     /// async fn io_func() -> io::Result<()> {
806     ///     let addr = "127.0.0.1:8080";
807     ///     let peer_addr = "127.0.0.1:8081";
808     ///     let mut sock = UdpSocket::bind(addr).await?;
809     ///     let connected_sock = match sock.connect(peer_addr).await {
810     ///         Ok(socket) => socket,
811     ///         Err(e) => {
812     ///             return Err(e);
813     ///         }
814     ///     };
815     ///     assert_eq!(connected_sock.peer_addr()?, peer_addr.parse().unwrap());
816     ///     Ok(())
817     /// }
818     /// ```
peer_addr(&self) -> io::Result<SocketAddr>819     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
820         self.source.peer_addr()
821     }
822 
823     /// Sets the value of the `SO_BROADCAST` option for this socket.
824     /// When enabled, this socket is allowed to send packets to a broadcast
825     /// address.
826     ///
827     /// # Examples
828     ///
829     /// ```rust
830     /// use std::io;
831     ///
832     /// use ylong_runtime::net::UdpSocket;
833     ///
834     /// async fn io_func() -> io::Result<()> {
835     ///     let local_addr = "127.0.0.1:8080";
836     ///     let peer_addr = "127.0.0.1:8081";
837     ///     let socket = UdpSocket::bind(local_addr).await?;
838     ///     let connected_sock = match socket.connect(peer_addr).await {
839     ///         Ok(socket) => socket,
840     ///         Err(e) => {
841     ///             return Err(e);
842     ///         }
843     ///     };
844     ///     if connected_sock.broadcast()? == false {
845     ///         connected_sock.set_broadcast(true)?;
846     ///     }
847     ///     assert_eq!(connected_sock.broadcast()?, true);
848     ///     Ok(())
849     /// }
850     /// ```
set_broadcast(&self, on: bool) -> io::Result<()>851     pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
852         self.source.set_broadcast(on)
853     }
854 
855     /// Gets the value of the `SO_BROADCAST` option for this socket.
856     ///
857     /// # Examples
858     ///
859     /// ```rust
860     /// use std::io;
861     ///
862     /// use ylong_runtime::net::UdpSocket;
863     ///
864     /// async fn io_func() -> io::Result<()> {
865     ///     let local_addr = "127.0.0.1:8080";
866     ///     let peer_addr = "127.0.0.1:8081";
867     ///     let socket = UdpSocket::bind(local_addr).await?;
868     ///     let connected_sock = match socket.connect(peer_addr).await {
869     ///         Ok(socket) => socket,
870     ///         Err(e) => {
871     ///             return Err(e);
872     ///         }
873     ///     };
874     ///     assert_eq!(connected_sock.broadcast()?, false);
875     ///     Ok(())
876     /// }
877     /// ```
broadcast(&self) -> io::Result<bool>878     pub fn broadcast(&self) -> io::Result<bool> {
879         self.source.broadcast()
880     }
881 
882     /// Sets the value for the IP_TTL option on this socket.
883     ///
884     /// # Examples
885     ///
886     /// ```no_run
887     /// use std::io;
888     ///
889     /// use ylong_runtime::net::UdpSocket;
890     ///
891     /// async fn io_func() -> io::Result<()> {
892     ///     let local_addr = "127.0.0.1:8080";
893     ///     let peer_addr = "127.0.0.1:8081";
894     ///     let socket = UdpSocket::bind(local_addr).await?;
895     ///     let connect_socket = socket.connect(peer_addr).await?;
896     ///     connect_socket.set_ttl(100).expect("set_ttl call failed");
897     ///     Ok(())
898     /// }
899     /// ```
set_ttl(&self, ttl: u32) -> io::Result<()>900     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
901         self.source.set_ttl(ttl)
902     }
903 
904     /// Sets the value for the IP_TTL option on this socket.
905     ///
906     /// # Examples
907     ///
908     /// ```no_run
909     /// use std::io;
910     ///
911     /// use ylong_runtime::net::UdpSocket;
912     ///
913     /// async fn io_func() -> io::Result<()> {
914     ///     let local_addr = "127.0.0.1:8080";
915     ///     let peer_addr = "127.0.0.1:8081";
916     ///     let socket = UdpSocket::bind(local_addr).await?;
917     ///     let connect_socket = socket.connect(peer_addr).await?;
918     ///     connect_socket.set_ttl(100).expect("set_ttl call failed");
919     ///     assert_eq!(connect_socket.ttl().unwrap(), 100);
920     ///     Ok(())
921     /// }
922     /// ```
ttl(&self) -> io::Result<u32>923     pub fn ttl(&self) -> io::Result<u32> {
924         self.source.ttl()
925     }
926 
927     /// Sends data on the socket to the remote address that the socket is
928     /// connected to. The connect method will connect this socket to a
929     /// remote address. This method will fail if the socket is not
930     /// connected.
931     ///
932     /// # Return value
933     /// On success, the number of bytes sent is returned, otherwise, the
934     /// encountered error is returned.
935     ///
936     /// # Examples
937     ///
938     /// ```rust
939     /// use std::io;
940     ///
941     /// use ylong_runtime::net::UdpSocket;
942     ///
943     /// async fn io_func() -> io::Result<()> {
944     ///     let local_addr = "127.0.0.1:8080";
945     ///     let sock = UdpSocket::bind(local_addr).await?;
946     ///     let remote_addr = "127.0.0.1:8081";
947     ///     let connected_sock = match sock.connect(remote_addr).await {
948     ///         Ok(socket) => socket,
949     ///         Err(e) => {
950     ///             return Err(e);
951     ///         }
952     ///     };
953     ///     connected_sock.send(b"Hello").await?;
954     ///     Ok(())
955     /// }
956     /// ```
send(&self, buf: &[u8]) -> io::Result<usize>957     pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
958         self.source
959             .async_process(Interest::WRITABLE, || self.source.send(buf))
960             .await
961     }
962 
963     /// Attempts to send data on the socket to the remote address that the
964     /// socket is connected to. This method will fail if the socket is not
965     /// connected.
966     ///
967     /// The function is usually paired with `writable`.
968     ///
969     /// # Return value
970     /// The function returns:
971     /// * `Ok(n)` n is the number of bytes sent.
972     /// * `Err(e)` if an error is encountered.
973     /// When the remote cannot receive the message, an
974     /// [`io::ErrorKind::WouldBlock`] will be returned.
975     ///
976     /// # Examples
977     ///
978     /// ```rust
979     /// use std::io;
980     ///
981     /// use ylong_runtime::net::UdpSocket;
982     ///
983     /// async fn io_func() -> io::Result<()> {
984     ///     let local_addr = "127.0.0.1:8080";
985     ///     let sock = UdpSocket::bind(local_addr).await?;
986     ///     let remote_addr = "127.0.0.1:8081";
987     ///     let connected_sock = match sock.connect(remote_addr).await {
988     ///         Ok(socket) => socket,
989     ///         Err(e) => {
990     ///             return Err(e);
991     ///         }
992     ///     };
993     ///     connected_sock.try_send(b"Hello")?;
994     ///     Ok(())
995     /// }
996     /// ```
try_send(&self, buf: &[u8]) -> io::Result<usize>997     pub fn try_send(&self, buf: &[u8]) -> io::Result<usize> {
998         self.source
999             .try_io(Interest::WRITABLE, || self.source.send(buf))
1000     }
1001 
1002     /// Attempts to send data on the socket to the remote address to which it
1003     /// was previously connected. The connect method will connect this
1004     /// socket to a remote address. This method will fail if the socket is
1005     /// not connected. Note that on multiple calls to a poll_* method in the
1006     /// send direction, only the Waker from the Context passed to the most
1007     /// recent call will be scheduled to receive a wakeup.
1008     ///
1009     /// # Return value
1010     /// The function returns:
1011     /// * `Poll::Pending` if the socket is not available to write
1012     /// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent
1013     /// * `Poll::Ready(Err(e))` if an error is encountered.
1014     ///
1015     /// # Examples
1016     ///
1017     /// ```rust
1018     /// use std::io;
1019     ///
1020     /// use ylong_runtime::futures::poll_fn;
1021     /// use ylong_runtime::net::UdpSocket;
1022     ///
1023     /// async fn io_func() -> io::Result<()> {
1024     ///     let local_addr = "127.0.0.1:8080";
1025     ///     let sock = UdpSocket::bind(local_addr).await?;
1026     ///     let remote_addr = "127.0.0.1:8081";
1027     ///     let connected_sock = match sock.connect(remote_addr).await {
1028     ///         Ok(socket) => socket,
1029     ///         Err(e) => {
1030     ///             return Err(e);
1031     ///         }
1032     ///     };
1033     ///     poll_fn(|cx| connected_sock.poll_send(cx, b"Hello")).await?;
1034     ///     Ok(())
1035     /// }
1036     /// ```
poll_send(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>>1037     pub fn poll_send(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
1038         self.source.poll_write_io(cx, || self.source.send(buf))
1039     }
1040 
1041     /// Receives a single datagram message on the socket from the remote address
1042     /// to which it is connected. On success, returns the number of bytes
1043     /// read. The function must be called with valid byte array buf of
1044     /// sufficient size to hold the message bytes. If a message is too long
1045     /// to fit in the supplied buffer, excess bytes may be discarded.
1046     /// The connect method will connect this socket to a remote address.
1047     /// This method will fail if the socket is not connected.
1048     ///
1049     /// # Return value
1050     /// The function returns:
1051     /// * `Ok(n)` n is is the number of bytes received
1052     /// * `Err(e)` if an error is encountered.
1053     ///
1054     /// # Examples
1055     ///
1056     /// ```rust
1057     /// use std::io;
1058     ///
1059     /// use ylong_runtime::net::UdpSocket;
1060     ///
1061     /// async fn io_func() -> io::Result<()> {
1062     ///     let local_addr = "127.0.0.1:8080";
1063     ///     let sock = UdpSocket::bind(local_addr).await?;
1064     ///     let remote_addr = "127.0.0.1:8081";
1065     ///     let connected_sock = match sock.connect(remote_addr).await {
1066     ///         Ok(socket) => socket,
1067     ///         Err(e) => {
1068     ///             return Err(e);
1069     ///         }
1070     ///     };
1071     ///     let mut recv_buf = [0_u8; 12];
1072     ///     let n = connected_sock.recv(&mut recv_buf[..]).await?;
1073     ///     println!("received {} bytes {:?}", n, &recv_buf[..n]);
1074     ///     Ok(())
1075     /// }
1076     /// ```
recv(&self, buf: &mut [u8]) -> io::Result<usize>1077     pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1078         self.source
1079             .async_process(Interest::READABLE, || self.source.recv(buf))
1080             .await
1081     }
1082 
1083     /// Attempts to receive a single datagram message on the socket from the
1084     /// remote address to which it is connected.
1085     /// On success, returns the number of bytes read. The function must be
1086     /// called with valid byte array buf of sufficient size to hold the
1087     /// message bytes. If a message is too long to fit in the supplied
1088     /// buffer, excess bytes may be discarded. This method will fail if the
1089     /// socket is not connected.
1090     ///
1091     /// # Return value
1092     /// The function returns:
1093     /// * `Ok(n, addr)` n is the number of bytes received, addr is the address
1094     ///   of the remote.
1095     /// * `Err(e)` if an error is encountered.
1096     /// If there is no pending data, an [`io::ErrorKind::WouldBlock`] will be
1097     /// returned.
1098     ///
1099     /// # Examples
1100     ///
1101     /// ```rust
1102     /// use std::io;
1103     ///
1104     /// use ylong_runtime::net::UdpSocket;
1105     ///
1106     /// async fn io_func() -> io::Result<()> {
1107     ///     let local_addr = "127.0.0.1:8080";
1108     ///     let sock = UdpSocket::bind(local_addr).await?;
1109     ///     let remote_addr = "127.0.0.1:8081";
1110     ///     let connected_sock = match sock.connect(remote_addr).await {
1111     ///         Ok(socket) => socket,
1112     ///         Err(e) => {
1113     ///             return Err(e);
1114     ///         }
1115     ///     };
1116     ///     let mut recv_buf = [0_u8; 12];
1117     ///     let n = connected_sock.try_recv(&mut recv_buf[..])?;
1118     ///     println!("received {} bytes {:?}", n, &recv_buf[..n]);
1119     ///     Ok(())
1120     /// }
1121     /// ```
try_recv(&self, buf: &mut [u8]) -> io::Result<usize>1122     pub fn try_recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1123         self.source
1124             .try_io(Interest::READABLE, || self.source.recv(buf))
1125     }
1126 
1127     /// Attempts to receive a single datagram message on the socket from the
1128     /// remote address to which it is connected. The connect method will
1129     /// connect this socket to a remote address. This method resolves to an
1130     /// error if the socket is not connected. Note that on multiple calls to
1131     /// a poll_* method in the recv direction, only the Waker from the
1132     /// Context passed to the most recent call will be scheduled to receive a
1133     /// wakeup.
1134     ///
1135     /// # Return value
1136     /// The function returns:
1137     ///
1138     /// * `Poll::Pending` if the socket is not ready to read
1139     /// * `Poll::Ready(Ok(()))` reads data ReadBuf if the socket is ready
1140     /// * `Poll::Ready(Err(e))` if an error is encountered.
1141     ///
1142     /// # Examples
1143     ///
1144     /// ```rust
1145     /// use std::io;
1146     ///
1147     /// use ylong_runtime::futures::poll_fn;
1148     /// use ylong_runtime::io::ReadBuf;
1149     /// use ylong_runtime::net::UdpSocket;
1150     ///
1151     /// async fn io_func() -> io::Result<()> {
1152     ///     let local_addr = "127.0.0.1:8080";
1153     ///     let sock = UdpSocket::bind(local_addr).await?;
1154     ///     let remote_addr = "127.0.0.1:8081";
1155     ///     let connected_sock = match sock.connect(remote_addr).await {
1156     ///         Ok(socket) => socket,
1157     ///         Err(e) => {
1158     ///             return Err(e);
1159     ///         }
1160     ///     };
1161     ///     let mut recv_buf = [0_u8; 12];
1162     ///     let mut read = ReadBuf::new(&mut recv_buf);
1163     ///     poll_fn(|cx| connected_sock.poll_recv(cx, &mut read)).await?;
1164     ///     println!("received : {:?}", read.filled());
1165     ///     Ok(())
1166     /// }
1167     /// ```
poll_recv(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>>1168     pub fn poll_recv(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
1169         let ret = self.source.poll_read_io(cx, || unsafe {
1170             let slice = &mut *(buf.unfilled_mut() as *mut [MaybeUninit<u8>] as *mut [u8]);
1171             self.source.recv(slice)
1172         });
1173         let r_len = match ret {
1174             Poll::Ready(Ok(x)) => x,
1175             Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
1176             Poll::Pending => return Poll::Pending,
1177         };
1178         buf.assume_init(r_len);
1179         buf.advance(r_len);
1180 
1181         Poll::Ready(Ok(()))
1182     }
1183 
1184     /// Receives single datagram on the socket from the remote address to which
1185     /// it is connected, without removing the message from input queue. On
1186     /// success, returns the number of bytes peeked.
1187     ///
1188     /// # Examples
1189     ///
1190     /// ```rust
1191     /// use std::io;
1192     ///
1193     /// use ylong_runtime::net::UdpSocket;
1194     ///
1195     /// async fn io_func() -> io::Result<()> {
1196     ///     let local_addr = "127.0.0.1:8080";
1197     ///     let receiver_addr = "127.0.0.1:8081";
1198     ///     let socket = UdpSocket::bind(local_addr).await?;
1199     ///     let connect_socket = socket
1200     ///         .connect(receiver_addr)
1201     ///         .await
1202     ///         .expect("connect function failed");
1203     ///     let mut buf = [0; 10];
1204     ///     match connect_socket.peek(&mut buf).await {
1205     ///         Ok(received) => println!("received {received} bytes"),
1206     ///         Err(e) => println!("peek function failed: {e:?}"),
1207     ///     }
1208     ///     Ok(())
1209     /// }
1210     /// ```
peek(&self, buf: &mut [u8]) -> io::Result<usize>1211     pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1212         self.source
1213             .async_process(Interest::READABLE, || self.source.peek(buf))
1214             .await
1215     }
1216 
1217     /// Attempts to Receives single datagram on the socket from the remote
1218     /// address to which it is connected, without removing the message from
1219     /// input queue. On success, returns the number of bytes peeked.
1220     ///
1221     /// # Examples
1222     ///
1223     /// ```rust
1224     /// use std::io;
1225     ///
1226     /// use ylong_runtime::net::UdpSocket;
1227     ///
1228     /// async fn io_func() -> io::Result<()> {
1229     ///     let local_addr = "127.0.0.1:8080";
1230     ///     let receiver_addr = "127.0.0.1:8081";
1231     ///     let socket = UdpSocket::bind(local_addr).await?;
1232     ///     let connect_socket = socket
1233     ///         .connect(receiver_addr)
1234     ///         .await
1235     ///         .expect("connect function failed");
1236     ///     let mut buf = [0; 10];
1237     ///     match connect_socket.try_peek(&mut buf) {
1238     ///         Ok(received) => println!("received {received} bytes"),
1239     ///         Err(e) => println!("try_peek function failed: {e:?}"),
1240     ///     }
1241     ///     Ok(())
1242     /// }
1243     /// ```
try_peek(&self, buf: &mut [u8]) -> io::Result<usize>1244     pub fn try_peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1245         self.source
1246             .try_io(Interest::READABLE, || self.source.peek(buf))
1247     }
1248 
1249     /// Waits for the socket to become readable.
1250     ///
1251     /// This function is usually paired up with [`UdpSocket::try_recv_from`]
1252     ///
1253     /// # Examples
1254     ///
1255     /// ```
1256     /// use std::io;
1257     ///
1258     /// use ylong_runtime::net::{ConnectedUdpSocket, UdpSocket};
1259     ///
1260     /// async fn io_func() -> io::Result<()> {
1261     ///     let local_addr = "127.0.0.1:8080";
1262     ///     let sock = UdpSocket::bind(local_addr).await?;
1263     ///     let remote_addr = "127.0.0.1:8081";
1264     ///     let connected_sock = match sock.connect(remote_addr).await {
1265     ///         Ok(socket) => socket,
1266     ///         Err(e) => {
1267     ///             return Err(e);
1268     ///         }
1269     ///     };
1270     ///     connected_sock.readable().await?;
1271     ///     let mut buf = [0; 12];
1272     ///     let len = connected_sock.try_recv(&mut buf)?;
1273     ///     Ok(())
1274     /// }
1275     /// ```
readable(&self) -> io::Result<()>1276     pub async fn readable(&self) -> io::Result<()> {
1277         self.source.entry.readiness(Interest::READABLE).await?;
1278         Ok(())
1279     }
1280 
1281     /// Waits for the socket to become writable.
1282     ///
1283     /// This function is usually paired up with [`UdpSocket::try_send_to`]
1284     ///
1285     /// # Examples
1286     ///
1287     /// ```
1288     /// use std::io;
1289     ///
1290     /// use ylong_runtime::net::{ConnectedUdpSocket, UdpSocket};
1291     ///
1292     /// async fn io_func() -> io::Result<()> {
1293     ///     let local_addr = "127.0.0.1:8080";
1294     ///     let sock = UdpSocket::bind(local_addr).await?;
1295     ///     let remote_addr = "127.0.0.1:8081";
1296     ///     let connected_sock = match sock.connect(remote_addr).await {
1297     ///         Ok(socket) => socket,
1298     ///         Err(e) => {
1299     ///             return Err(e);
1300     ///         }
1301     ///     };
1302     ///     connected_sock.writable().await?;
1303     ///     let mut buf = [0; 12];
1304     ///     let len = connected_sock.try_send(&mut buf)?;
1305     ///     Ok(())
1306     /// }
1307     /// ```
writable(&self) -> io::Result<()>1308     pub async fn writable(&self) -> io::Result<()> {
1309         self.source.entry.readiness(Interest::WRITABLE).await?;
1310         Ok(())
1311     }
1312 
1313     /// Gets the value of the SO_ERROR option on this socket.
1314     ///
1315     /// # Examples
1316     ///
1317     /// ```no_run
1318     /// use std::io;
1319     ///
1320     /// use ylong_runtime::net::UdpSocket;
1321     ///
1322     /// async fn io_func() -> io::Result<()> {
1323     ///     let local_addr = "127.0.0.1:8080";
1324     ///     let socket = UdpSocket::bind(local_addr)
1325     ///         .await
1326     ///         .expect("couldn't bind to address");
1327     ///     let remote_addr = "127.0.0.1:8081";
1328     ///     let connected_sock = match socket.connect(remote_addr).await {
1329     ///         Ok(socket) => socket,
1330     ///         Err(e) => {
1331     ///             return Err(e);
1332     ///         }
1333     ///     };
1334     ///     match connected_sock.take_error() {
1335     ///         Ok(Some(error)) => println!("UdpSocket error: {error:?}"),
1336     ///         Ok(None) => println!("No error"),
1337     ///         Err(error) => println!("UdpSocket.take_error failed: {error:?}"),
1338     ///     }
1339     ///     Ok(())
1340     /// }
1341     /// ```
take_error(&self) -> io::Result<Option<io::Error>>1342     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1343         self.source.take_error()
1344     }
1345 
1346     /// Gets the value of the IP_MULTICAST_LOOP option for this socket.
multicast_loop_v4(&self) -> io::Result<bool>1347     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
1348         self.source.multicast_loop_v4()
1349     }
1350 
1351     /// Sets the value of the IP_MULTICAST_LOOP option for this socket.
1352     /// If enabled, multicast packets will be looped back to the local socket.
1353     /// Note that this might not have any effect on IPv6 sockets.
set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()>1354     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
1355         self.source.set_multicast_loop_v4(multicast_loop_v4)
1356     }
1357 
1358     /// Gets the value of the IP_MULTICAST_TTL option for this socket.
multicast_ttl_v4(&self) -> io::Result<u32>1359     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
1360         self.source.multicast_ttl_v4()
1361     }
1362 
1363     /// Sets the value of the IP_MULTICAST_TTL option for this socket.
1364     /// Indicates the time-to-live value of outgoing multicast packets for this
1365     /// socket. The default value is 1 which means that multicast packets don't
1366     /// leave the local network unless explicitly requested. Note that this
1367     /// might not have any effect on IPv6 sockets.
set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()>1368     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
1369         self.source.set_multicast_ttl_v4(multicast_ttl_v4)
1370     }
1371 
1372     /// Gets the value of the IPV6_MULTICAST_LOOP option for this socket.
multicast_loop_v6(&self) -> io::Result<bool>1373     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
1374         self.source.multicast_loop_v6()
1375     }
1376 
1377     /// Sets the value of the IPV6_MULTICAST_LOOP option for this socket.
1378     /// Controls whether this socket sees the multicast packets it sends itself.
1379     /// Note that this might not have any affect on IPv4 sockets.
set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()>1380     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
1381         self.source.set_multicast_loop_v6(multicast_loop_v6)
1382     }
1383 
1384     /// Executes an operation of the IP_ADD_MEMBERSHIP type.
join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>1385     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
1386         self.source.join_multicast_v4(multiaddr, interface)
1387     }
1388 
1389     /// Executes an operation of the IPV6_ADD_MEMBERSHIP type.
join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>1390     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
1391         self.source.join_multicast_v6(multiaddr, interface)
1392     }
1393 
1394     /// Executes an operation of the IP_DROP_MEMBERSHIP type.
leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>1395     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
1396         self.source.leave_multicast_v4(multiaddr, interface)
1397     }
1398 
1399     /// Executes an operation of the IPV6_DROP_MEMBERSHIP type.
leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>1400     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
1401         self.source.leave_multicast_v6(multiaddr, interface)
1402     }
1403 }
1404 
1405 #[cfg(windows)]
1406 use std::os::windows::io::{AsRawSocket, RawSocket};
1407 
1408 #[cfg(windows)]
1409 impl AsRawSocket for UdpSocket {
as_raw_socket(&self) -> RawSocket1410     fn as_raw_socket(&self) -> RawSocket {
1411         self.source.as_raw_socket()
1412     }
1413 }
1414 
1415 #[cfg(windows)]
1416 impl AsRawSocket for ConnectedUdpSocket {
as_raw_socket(&self) -> RawSocket1417     fn as_raw_socket(&self) -> RawSocket {
1418         self.source.as_raw_socket()
1419     }
1420 }
1421 
1422 #[cfg(unix)]
1423 use std::os::fd::{AsRawFd, RawFd};
1424 
1425 #[cfg(unix)]
1426 use ylong_io::Source;
1427 
1428 #[cfg(unix)]
1429 impl AsRawFd for UdpSocket {
as_raw_fd(&self) -> RawFd1430     fn as_raw_fd(&self) -> RawFd {
1431         self.source.get_fd()
1432     }
1433 }
1434 
1435 #[cfg(unix)]
1436 impl AsRawFd for ConnectedUdpSocket {
as_raw_fd(&self) -> RawFd1437     fn as_raw_fd(&self) -> RawFd {
1438         self.source.get_fd()
1439     }
1440 }
1441 
1442 #[cfg(test)]
1443 mod tests {
1444     use std::io;
1445     use std::net::{Ipv4Addr, Ipv6Addr};
1446 
1447     use crate::futures::poll_fn;
1448     use crate::io::ReadBuf;
1449     use crate::net::{ConnectedUdpSocket, UdpSocket};
1450     use crate::{block_on, spawn};
1451 
1452     const ADDR: &str = "127.0.0.1:0";
1453 
1454     // Try to bind a udp in local_addr and connect to peer_addr, Either of the two
1455     // has an AddrInUse error will retry until success.
udp_try_bind_connect<F>( addr: &str, mut f: F, ) -> io::Result<(ConnectedUdpSocket, ConnectedUdpSocket)> where F: FnMut(&UdpSocket),1456     async fn udp_try_bind_connect<F>(
1457         addr: &str,
1458         mut f: F,
1459     ) -> io::Result<(ConnectedUdpSocket, ConnectedUdpSocket)>
1460     where
1461         F: FnMut(&UdpSocket),
1462     {
1463         loop {
1464             let local_udp_socket = UdpSocket::bind(addr).await?;
1465             let peer_udp_socket = UdpSocket::bind(addr).await?;
1466 
1467             f(&local_udp_socket);
1468 
1469             let local_addr = local_udp_socket.local_addr().unwrap();
1470             let peer_addr = peer_udp_socket.local_addr().unwrap();
1471             let local_connect = match local_udp_socket.connect(peer_addr).await {
1472                 Ok(socket) => socket,
1473                 Err(e) if e.kind() == io::ErrorKind::AddrInUse => continue,
1474                 Err(e) => return Err(e),
1475             };
1476             let peer_connect = match peer_udp_socket.connect(local_addr).await {
1477                 Ok(socket) => socket,
1478                 Err(e) if e.kind() == io::ErrorKind::AddrInUse => continue,
1479                 Err(e) => return Err(e),
1480             };
1481             return Ok((local_connect, peer_connect));
1482         }
1483     }
1484 
1485     /// Basic UT test cases for `UdpSocket` with `SocketAddrV4`.
1486     ///
1487     /// # Brief
1488     /// 1. Bind and connect `UdpSocket`.
1489     /// 2. Call set_ttl(), ttl(), take_error(), set_multicast_loop_v4(),
1490     ///    multicast_loop_v4(), set_multicast_ttl_v4(), multicast_ttl_v4() for
1491     ///    `UdpSocket` and `ConnectedUdpSocket`.
1492     /// 3. Check result is correct.
1493     #[test]
ut_udp_basic_v4()1494     fn ut_udp_basic_v4() {
1495         block_on(async {
1496             let interface = Ipv4Addr::new(0, 0, 0, 0);
1497             let mut multi_addr = None;
1498 
1499             let socket_deal = |sender: &UdpSocket| {
1500                 sender.set_ttl(101).unwrap();
1501                 assert_eq!(sender.ttl().unwrap(), 101);
1502                 assert!(sender.take_error().unwrap().is_none());
1503                 sender.set_multicast_loop_v4(false).unwrap();
1504                 assert!(!sender.multicast_loop_v4().unwrap());
1505                 sender.set_multicast_ttl_v4(42).unwrap();
1506                 assert_eq!(sender.multicast_ttl_v4().unwrap(), 42);
1507 
1508                 for i in 0..255 {
1509                     let addr = Ipv4Addr::new(224, 0, 0, i);
1510                     if sender.join_multicast_v4(&addr, &interface).is_ok() {
1511                         multi_addr = Some(addr);
1512                         break;
1513                     }
1514                 }
1515 
1516                 if let Some(addr) = multi_addr {
1517                     sender
1518                         .leave_multicast_v4(&addr, &interface)
1519                         .expect("Cannot leave the multicast group");
1520                 }
1521             };
1522 
1523             let (connected_sender, _) = udp_try_bind_connect(ADDR, socket_deal).await.unwrap();
1524 
1525             connected_sender.set_ttl(101).unwrap();
1526             assert_eq!(connected_sender.ttl().unwrap(), 101);
1527             assert!(connected_sender.take_error().unwrap().is_none());
1528             connected_sender.set_multicast_loop_v4(false).unwrap();
1529             assert!(!connected_sender.multicast_loop_v4().unwrap());
1530             connected_sender.set_multicast_ttl_v4(42).unwrap();
1531             assert_eq!(connected_sender.multicast_ttl_v4().unwrap(), 42);
1532 
1533             if let Some(addr) = multi_addr {
1534                 connected_sender
1535                     .join_multicast_v4(&addr, &interface)
1536                     .expect("Cannot join the multicast group");
1537                 connected_sender
1538                     .leave_multicast_v4(&multi_addr.unwrap(), &interface)
1539                     .expect("Cannot leave the multicast group");
1540             }
1541         });
1542     }
1543 
1544     /// Basic UT test cases for `UdpSocket` with `SocketAddrV6`.
1545     ///
1546     /// # Brief
1547     /// 1. Bind and connect `UdpSocket`.
1548     /// 2. Call set_multicast_loop_v6(), multicast_loop_v6() for `UdpSocket` and
1549     ///    `ConnectedUdpSocket`.
1550     /// 3. Check result is correct.
1551     #[test]
ut_udp_basic_v6()1552     fn ut_udp_basic_v6() {
1553         block_on(async {
1554             let addr = "::1:0";
1555 
1556             let interface = 1_u32;
1557             let mut multi_addr = None;
1558             let socket_deal = |sender: &UdpSocket| {
1559                 sender.set_multicast_loop_v6(false).unwrap();
1560                 assert!(!sender.multicast_loop_v6().unwrap());
1561 
1562                 for i in 10..0xFFFF {
1563                     let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, i);
1564                     if sender.join_multicast_v6(&addr, interface).is_ok() {
1565                         multi_addr = Some(addr);
1566                         break;
1567                     }
1568                 }
1569 
1570                 if let Some(addr) = multi_addr {
1571                     sender
1572                         .leave_multicast_v6(&addr, interface)
1573                         .expect("Cannot leave the multicast group");
1574                 }
1575             };
1576             let (connected_sender, _) = udp_try_bind_connect(addr, socket_deal).await.unwrap();
1577 
1578             connected_sender.set_multicast_loop_v6(false).unwrap();
1579             assert!(!connected_sender.multicast_loop_v6().unwrap());
1580 
1581             if let Some(addr) = multi_addr {
1582                 connected_sender
1583                     .join_multicast_v6(&addr, interface)
1584                     .expect("Cannot join the multicast group");
1585                 connected_sender
1586                     .leave_multicast_v6(&addr, interface)
1587                     .expect("Cannot leave the multicast group");
1588             }
1589         });
1590     }
1591 
1592     /// UT test cases for `poll_send()` and `poll_recv()`.
1593     ///
1594     /// # Brief
1595     /// 1. Create UdpSocket and connect to the remote address.
1596     /// 2. Sender calls poll_fn() to send message first.
1597     /// 3. Receiver calls poll_fn() to receive message.
1598     /// 4. Check if the test results are correct.
1599     #[test]
ut_send_recv_poll()1600     fn ut_send_recv_poll() {
1601         let handle = spawn(async move {
1602             let (connected_sender, connected_receiver) =
1603                 udp_try_bind_connect(ADDR, |_| {}).await.unwrap();
1604             let n = poll_fn(|cx| connected_sender.poll_send(cx, b"Hello"))
1605                 .await
1606                 .expect("Sender Send Failed");
1607             assert_eq!(n, "Hello".len());
1608 
1609             let mut recv_buf = [0_u8; 12];
1610             let mut read = ReadBuf::new(&mut recv_buf);
1611             poll_fn(|cx| connected_receiver.poll_recv(cx, &mut read))
1612                 .await
1613                 .unwrap();
1614 
1615             assert_eq!(read.filled(), b"Hello");
1616         });
1617         block_on(handle).expect("block_on failed");
1618     }
1619 
1620     /// UT test cases for `poll_send_to()` and `poll_recv_from()`.
1621     ///
1622     /// # Brief
1623     /// 1. Create UdpSocket.
1624     /// 2. Sender calls poll_fn() to send message to the specified address.
1625     /// 3. Receiver calls poll_fn() to receive message and return the address
1626     ///    the message from.
1627     /// 4. Check if the test results are correct.
1628     #[test]
ut_send_to_recv_from_poll()1629     fn ut_send_to_recv_from_poll() {
1630         let handle = spawn(async move {
1631             let sender = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1632             let receiver = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1633 
1634             let sender_addr = sender.local_addr().unwrap();
1635             let receiver_addr = receiver.local_addr().unwrap();
1636             let n = poll_fn(|cx| sender.poll_send_to(cx, b"Hello", receiver_addr))
1637                 .await
1638                 .expect("Sender Send Failed");
1639             assert_eq!(n, "Hello".len());
1640 
1641             let mut recv_buf = [0_u8; 12];
1642             let mut read = ReadBuf::new(&mut recv_buf);
1643             let addr = poll_fn(|cx| receiver.poll_recv_from(cx, &mut read))
1644                 .await
1645                 .unwrap();
1646             assert_eq!(read.filled(), b"Hello");
1647             assert_eq!(addr, sender_addr);
1648         });
1649         block_on(handle).expect("block_on failed");
1650     }
1651 
1652     /// UT test cases for `broadcast()` and `set_broadcast()`.
1653     ///
1654     /// # Brief
1655     /// 1. Create UdpSocket.
1656     /// 2. Sender calls set_broadcast() to set broadcast.
1657     /// 3. Sender calls broadcast() to get broadcast.
1658     /// 4. Check if the test results are correct.
1659     #[test]
ut_set_get_broadcast()1660     fn ut_set_get_broadcast() {
1661         let handle = spawn(async move {
1662             let broadcast_socket = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1663             broadcast_socket
1664                 .set_broadcast(true)
1665                 .expect("set_broadcast failed");
1666 
1667             assert!(broadcast_socket.broadcast().expect("get broadcast failed"));
1668         });
1669         block_on(handle).expect("block_on failed");
1670 
1671         let handle = spawn(async move {
1672             let (broadcast_socket, _) = udp_try_bind_connect(ADDR, |_| {}).await.unwrap();
1673             broadcast_socket
1674                 .set_broadcast(true)
1675                 .expect("set_broadcast failed");
1676 
1677             assert!(broadcast_socket.broadcast().expect("get broadcast failed"));
1678         });
1679         block_on(handle).expect("block_on failed");
1680     }
1681 
1682     /// UT test cases for `local_addr()`.
1683     ///
1684     /// # Brief
1685     /// 1. Create UdpSocket.
1686     /// 2. Sender calls local_addr() to get local address.
1687     /// 3. Check if the test results are correct.
1688     #[test]
ut_get_local_addr()1689     fn ut_get_local_addr() {
1690         let handle = spawn(async move {
1691             let mut local_addr = None;
1692             let socket_deal = |socket: &UdpSocket| local_addr = Some(socket.local_addr().unwrap());
1693             let (connected_sock, _) = udp_try_bind_connect(ADDR, socket_deal).await.unwrap();
1694 
1695             let connect_local_addr = connected_sock.local_addr().expect("local_addr failed");
1696             assert_eq!(connect_local_addr, local_addr.unwrap());
1697         });
1698         block_on(handle).expect("block_on failed");
1699     }
1700 
1701     /// UT test cases for `peer_addr()`.
1702     ///
1703     /// # Brief
1704     /// 1. Create UdpSocket.
1705     /// 2. Sender calls peer_addr() to get the socket address of the remote
1706     ///    peer.
1707     /// 3. Check if the test results are correct.
1708     #[test]
ut_get_peer_addr()1709     fn ut_get_peer_addr() {
1710         let handle = spawn(async move {
1711             let mut local_addr = None;
1712             let socket_deal = |socket: &UdpSocket| local_addr = Some(socket.local_addr().unwrap());
1713             let (_, peer_socket) = udp_try_bind_connect(ADDR, socket_deal).await.unwrap();
1714 
1715             assert_eq!(
1716                 peer_socket.peer_addr().expect("peer_addr failed"),
1717                 local_addr.unwrap()
1718             );
1719         });
1720         block_on(handle).expect("block_on failed");
1721     }
1722 
1723     /// UT test cases for `send_to()` and `peek_from()`.
1724     ///
1725     /// # Brief
1726     /// 1. Create UdpSocket.
1727     /// 2. Sender calls send_to() to send message to the specified address.
1728     /// 3. Receiver calls peek_from() to receive message and return the number
1729     ///    of bytes peeked.
1730     /// 4. Check if the test results are correct.
1731     #[test]
ut_send_to_peek_from()1732     fn ut_send_to_peek_from() {
1733         let handle = spawn(async move {
1734             let sender = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1735             let receiver = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1736 
1737             let receiver_addr = receiver.local_addr().unwrap();
1738             let buf = [2; 6];
1739             sender
1740                 .send_to(&buf, receiver_addr)
1741                 .await
1742                 .expect("Send data Failed");
1743 
1744             let mut buf = [0; 10];
1745             let (number_of_bytes, _) = receiver
1746                 .peek_from(&mut buf)
1747                 .await
1748                 .expect("Didn't receive data");
1749 
1750             assert_eq!(number_of_bytes, 6);
1751         });
1752 
1753         block_on(handle).expect("block_on failed");
1754     }
1755 
1756     /// UT test cases for `send_to()` and `try_peek_from()`.
1757     ///
1758     /// # Brief
1759     /// 1. Create UdpSocket.
1760     /// 2. Sender calls send_to() to send message to the specified address.
1761     /// 3. Receiver calls readable() to wait for the socket to become readable.
1762     /// 4. Receiver calls try_peek_from() to receive message and return the
1763     ///    number of bytes peeked.
1764     /// 5. Check if the test results are correct.
1765     #[test]
ut_send_to_try_peek_from()1766     fn ut_send_to_try_peek_from() {
1767         let handle = spawn(async move {
1768             let sender = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1769             let receiver = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1770 
1771             let receiver_addr = receiver.local_addr().unwrap();
1772 
1773             let buf = [2; 6];
1774             let number_of_bytes = sender
1775                 .send_to(&buf, receiver_addr)
1776                 .await
1777                 .expect("Send data Failed");
1778             assert_eq!(number_of_bytes, 6);
1779 
1780             let mut buf = [0; 10];
1781             receiver.readable().await.expect("Receiver isn't readable");
1782             let (number_of_bytes, _) = receiver
1783                 .try_peek_from(&mut buf)
1784                 .expect("Didn't receive data");
1785             assert_eq!(number_of_bytes, 6);
1786         });
1787 
1788         block_on(handle).expect("block_on failed");
1789     }
1790 
1791     /// UT test cases for `poll_send_to()` and `poll_peek_from()`.
1792     ///
1793     /// # Brief
1794     /// 1. Create UdpSocket.
1795     /// 2. Sender calls poll_fn() to send message to the specified address.
1796     /// 3. Receiver calls poll_fn() to receive message and return the address
1797     ///    the message from.
1798     /// 4. Check if the test results are correct.
1799     #[test]
ut_send_to_peek_from_poll()1800     fn ut_send_to_peek_from_poll() {
1801         let handle = spawn(async move {
1802             let sender = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1803             let receiver = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1804 
1805             let sender_addr = sender.local_addr().unwrap();
1806             let receiver_addr = receiver.local_addr().unwrap();
1807 
1808             let n = poll_fn(|cx| sender.poll_send_to(cx, b"Hello", receiver_addr))
1809                 .await
1810                 .expect("Sender Send Failed");
1811             assert_eq!(n, "Hello".len());
1812 
1813             let mut recv_buf = [0_u8; 12];
1814             let mut read = ReadBuf::new(&mut recv_buf);
1815             let addr = poll_fn(|cx| receiver.poll_peek_from(cx, &mut read))
1816                 .await
1817                 .unwrap();
1818             assert_eq!(read.filled(), b"Hello");
1819             assert_eq!(addr, sender_addr);
1820         });
1821         block_on(handle).expect("block_on failed");
1822     }
1823 
1824     /// UT test cases for `peek()` in ConnectedUdpSocket.
1825     ///
1826     /// # Brief
1827     /// 1. Create UdpSocket.
1828     /// 2. Sender calls send_to() to send message to the specified address.
1829     /// 3. Receiver calls connect() to create a ConnectedUdpSocket.
1830     /// 4. ConnectedUdpSocket calls peek() to receive message.
1831     /// 5. Check if the test results are correct.
1832     #[test]
ut_connected_peek()1833     fn ut_connected_peek() {
1834         let handle = spawn(async move {
1835             let sender = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1836             let receiver = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1837 
1838             let sender_addr = sender.local_addr().unwrap();
1839             let receiver_addr = receiver.local_addr().unwrap();
1840 
1841             let connect_socket = receiver.connect(sender_addr).await.unwrap();
1842 
1843             let send_buf = [2; 6];
1844             sender
1845                 .send_to(&send_buf, receiver_addr)
1846                 .await
1847                 .expect("Send data Failed");
1848 
1849             let mut buf = [0; 10];
1850             let number_of_bytes = connect_socket
1851                 .peek(&mut buf)
1852                 .await
1853                 .expect("Didn't receive data");
1854 
1855             assert_eq!(number_of_bytes, 6);
1856         });
1857 
1858         block_on(handle).expect("block_on failed");
1859     }
1860 
1861     /// UT test cases for `try_peek()` in ConnectedUdpSocket.
1862     ///
1863     /// # Brief
1864     /// 1. Create UdpSocket.
1865     /// 2. Sender calls send_to() to send message to the specified address.
1866     /// 3. Receiver calls connect() to create a ConnectedUdpSocket.
1867     /// 4. ConnectedUdpSocket waits to be readable, then calls try_peek() to
1868     ///    receive message.
1869     /// 5. Check if the test results are correct.
1870     #[test]
ut_connected_try_peek()1871     fn ut_connected_try_peek() {
1872         let handle = spawn(async move {
1873             let sender = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1874             let receiver = UdpSocket::bind(ADDR).await.expect("Bind Socket Failed");
1875 
1876             let sender_addr = sender.local_addr().unwrap();
1877             let receiver_addr = receiver.local_addr().unwrap();
1878 
1879             let connect_socket = receiver.connect(sender_addr).await.unwrap();
1880 
1881             let send_buf = [2; 6];
1882             sender
1883                 .send_to(&send_buf, receiver_addr)
1884                 .await
1885                 .expect("Send data Failed");
1886 
1887             let mut buf = [0; 10];
1888             connect_socket.readable().await.unwrap();
1889             let number_of_bytes = connect_socket
1890                 .try_peek(&mut buf)
1891                 .expect("Didn't receive data");
1892 
1893             assert_eq!(number_of_bytes, 6);
1894         });
1895 
1896         block_on(handle).expect("block_on failed");
1897     }
1898 }
1899