net: add peer_addr to UdpSocket (#4611)

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
This commit is contained in:
Bruno
2022-04-10 01:52:45 +00:00
committed by GitHub
parent 83477c725a
commit 252b0fa9d5
+22
View File
@@ -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::<SocketAddr>().unwrap();
/// let peer = "127.0.0.1:11100".parse::<SocketAddr>().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<SocketAddr> {
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`.