From 9fa3ce3fd6125404f17901cda878897016c33584 Mon Sep 17 00:00:00 2001 From: Afirez <707627402@qq.com> Date: Sun, 14 Jun 2020 18:45:27 +0800 Subject: [PATCH] Add UdpSocket::PeerAddr #307 --- src/net/udp/mod.rs | 26 ++++++++++++++++++++++++++ tests/udp.rs | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/net/udp/mod.rs b/src/net/udp/mod.rs index 30cceb7..18f6fc7 100644 --- a/src/net/udp/mod.rs +++ b/src/net/udp/mod.rs @@ -88,6 +88,32 @@ impl UdpSocket { })) } + /// Returns the peer address that this listener is connected to. + /// + /// This can be useful, for example, when connect to port 0 to figure out which port was + /// actually connected. + /// + /// # Examples + /// + /// ```no_run + /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async { + /// # + /// use async_std::net::UdpSocket; + /// + /// let socket1 = UdpSocket::bind("127.0.0.1:0").await?; + /// let socket2 = UdpSocket::bind("127.0.0.1:0").await?; + /// socket1.connect(socket2.local_addr()?).await?; + /// let addr = socket1.peer_addr()?; + /// # + /// # Ok(()) }) } + /// ``` + pub fn peer_addr(&self) -> io::Result { + self.watcher + .get_ref() + .peer_addr() + .context(|| String::from("could not get peer address")) + } + /// Returns the local address that this listener is bound to. /// /// This can be useful, for example, when binding to port 0 to figure out which port was diff --git a/tests/udp.rs b/tests/udp.rs index 15404f8..37024c4 100644 --- a/tests/udp.rs +++ b/tests/udp.rs @@ -19,7 +19,7 @@ fn send_recv() -> io::Result<()> { socket1.connect(socket2.local_addr()?).await?; socket2.connect(socket1.local_addr()?).await?; - + assert_eq!(socket1.peer_addr()?, socket2.local_addr()?); socket1.send(THE_MERCHANT_OF_VENICE).await?; let mut buf = [0u8; 1024];