Skip to content

Commit a602a91

Browse files
authored
Merge pull request #816 from zhaxzhax/add-udpscket-peeraddr
Add UdpSocket::PeerAddr #307
2 parents 5c2a3de + 9fa3ce3 commit a602a91

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/net/udp/mod.rs

+26
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,32 @@ impl UdpSocket {
8888
}))
8989
}
9090

91+
/// Returns the peer address that this listener is connected to.
92+
///
93+
/// This can be useful, for example, when connect to port 0 to figure out which port was
94+
/// actually connected.
95+
///
96+
/// # Examples
97+
///
98+
/// ```no_run
99+
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
100+
/// #
101+
/// use async_std::net::UdpSocket;
102+
///
103+
/// let socket1 = UdpSocket::bind("127.0.0.1:0").await?;
104+
/// let socket2 = UdpSocket::bind("127.0.0.1:0").await?;
105+
/// socket1.connect(socket2.local_addr()?).await?;
106+
/// let addr = socket1.peer_addr()?;
107+
/// #
108+
/// # Ok(()) }) }
109+
/// ```
110+
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
111+
self.watcher
112+
.get_ref()
113+
.peer_addr()
114+
.context(|| String::from("could not get peer address"))
115+
}
116+
91117
/// Returns the local address that this listener is bound to.
92118
///
93119
/// This can be useful, for example, when binding to port 0 to figure out which port was

tests/udp.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ fn send_recv() -> io::Result<()> {
1919

2020
socket1.connect(socket2.local_addr()?).await?;
2121
socket2.connect(socket1.local_addr()?).await?;
22-
22+
assert_eq!(socket1.peer_addr()?, socket2.local_addr()?);
2323
socket1.send(THE_MERCHANT_OF_VENICE).await?;
2424

2525
let mut buf = [0u8; 1024];

0 commit comments

Comments
 (0)