Skip to content

Commit a9d9bde

Browse files
authored
net: add UdpSocket::peer_addr (#4362)
1 parent 0190831 commit a9d9bde

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

tokio/src/net/udp.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff 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`.

tokio/tests/udp.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
use futures::future::poll_fn;
55
use std::io;
6+
use std::net::SocketAddr;
67
use std::sync::Arc;
78
use tokio::{io::ReadBuf, net::UdpSocket};
89
use 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+
}

0 commit comments

Comments
 (0)