From c32709eeb8baca8a8cf5a22740da1168f260e89b Mon Sep 17 00:00:00 2001 From: PoorlyDefinedBehaviour Date: Sat, 9 Apr 2022 17:54:31 -0300 Subject: [PATCH] net: add peer_addr to UdpSocket The std UdpSocket has the peer_addr method which can be used to get the address of the remote peer the socket is connected to. Fixes: #4609 --- tokio/src/net/udp.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tokio/src/net/udp.rs b/tokio/src/net/udp.rs index eea6164b177..bd905e91a5f 100644 --- a/tokio/src/net/udp.rs +++ b/tokio/src/net/udp.rs @@ -278,6 +278,28 @@ impl UdpSocket { self.io.local_addr() } + /// Returns the socket address of the remote peer this socket was connected to. + /// + /// # Example + /// + /// ``` + /// use tokio::net::UdpSocket; + /// + /// # use std::{io, net::SocketAddr}; + /// # #[tokio::main] + /// # async fn main() -> io::Result<()> { + /// let addr = "0.0.0.0:8080".parse::().unwrap(); + /// let peer = "127.0.0.1:11100".parse::().unwrap(); + /// let sock = UdpSocket::bind(addr).await?; + /// sock.connect(peer).await?; + /// assert_eq!(peer, sock.peer_addr()?); + /// # Ok(()) + /// # } + /// ``` + pub fn peer_addr(&self) -> io::Result { + self.io.peer_addr() + } + /// Connects the UDP socket setting the default destination for send() and /// limiting packets that are read via recv from the address specified in /// `addr`.