File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed
Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -274,6 +274,29 @@ impl UdpSocket {
274274 self . io . local_addr ( )
275275 }
276276
277+ /// Returns the socket address of the remote peer this socket was connected
278+ /// to.
279+ ///
280+ /// # Example
281+ ///
282+ /// ```
283+ /// use tokio::net::UdpSocket;
284+ /// # use std::{io, net::SocketAddr};
285+ ///
286+ /// # #[tokio::main]
287+ /// # async fn main() -> io::Result<()> {
288+ /// let addr = "127.0.0.1:0".parse::<SocketAddr>().unwrap();
289+ /// let peer_addr = "127.0.0.1:11100".parse::<SocketAddr>().unwrap();
290+ /// let sock = UdpSocket::bind(addr).await?;
291+ /// sock.connect(peer_addr).await?;
292+ /// assert_eq!(sock.peer_addr()?.ip(), peer_addr.ip());
293+ /// # Ok(())
294+ /// # }
295+ /// ```
296+ pub fn peer_addr ( & self ) -> io:: Result < SocketAddr > {
297+ self . io . peer_addr ( )
298+ }
299+
277300 /// Connects the UDP socket setting the default destination for send() and
278301 /// limiting packets that are read via recv from the address specified in
279302 /// `addr`.
Original file line number Diff line number Diff line change 33
44use futures:: future:: poll_fn;
55use std:: io;
6+ use std:: net:: SocketAddr ;
67use std:: sync:: Arc ;
78use tokio:: { io:: ReadBuf , net:: UdpSocket } ;
89use tokio_test:: assert_ok;
@@ -484,3 +485,12 @@ async fn poll_ready() {
484485 }
485486 }
486487}
488+
489+ #[ tokio:: test]
490+ async fn peer_addr ( ) {
491+ let addr = "127.0.0.1:0" . parse :: < SocketAddr > ( ) . unwrap ( ) ;
492+ let peer_addr = "127.0.0.1:11100" . parse :: < SocketAddr > ( ) . unwrap ( ) ;
493+ let sock = UdpSocket :: bind ( addr) . await . unwrap ( ) ;
494+ sock. connect ( peer_addr) . await . unwrap ( ) ;
495+ assert_eq ! ( sock. peer_addr( ) . unwrap( ) . ip( ) , peer_addr. ip( ) ) ;
496+ }
You can’t perform that action at this time.
0 commit comments