net: add UdpSocket::peer_addr (#4362)

This commit is contained in:
Taiki Endo 2021-12-31 19:23:04 +09:00 committed by GitHub
parent 0190831ec1
commit a9d9bde068
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 0 deletions

View File

@ -274,6 +274,29 @@ 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 = "127.0.0.1:0".parse::<SocketAddr>().unwrap();
/// let peer_addr = "127.0.0.1:11100".parse::<SocketAddr>().unwrap();
/// let sock = UdpSocket::bind(addr).await?;
/// sock.connect(peer_addr).await?;
/// assert_eq!(sock.peer_addr()?.ip(), peer_addr.ip());
/// # 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`.

View File

@ -3,6 +3,7 @@
use futures::future::poll_fn;
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::{io::ReadBuf, net::UdpSocket};
use tokio_test::assert_ok;
@ -484,3 +485,12 @@ async fn poll_ready() {
}
}
}
#[tokio::test]
async fn peer_addr() {
let addr = "127.0.0.1:0".parse::<SocketAddr>().unwrap();
let peer_addr = "127.0.0.1:11100".parse::<SocketAddr>().unwrap();
let sock = UdpSocket::bind(addr).await.unwrap();
sock.connect(peer_addr).await.unwrap();
assert_eq!(sock.peer_addr().unwrap().ip(), peer_addr.ip());
}