API for obtaining our local endpoint

This is especially useful if we were binding to port 0 intending the OS to allocate us a random port. Then we would like to know what port was actually allocated. Besides it's a useful API anyway as it's natural to want to know this detail from a bound socket for completeness.
This commit is contained in:
ustulation
2019-03-19 16:53:38 +00:00
committed by Dirkjan Ochtman
parent 0a967f66e2
commit e468390802
3 changed files with 23 additions and 0 deletions
+5
View File
@@ -171,6 +171,11 @@ impl Endpoint {
Ok(())
}
/// Get the local endpoint the underlying socket is bound to
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.inner.borrow().socket.local_addr()
}
/*
/// Connect to a remote endpoint, with support for transmitting data before the connection is
/// established
+14
View File
@@ -8,6 +8,20 @@ use std::{
};
use tokio;
#[test]
fn local_addr() {
let port = 56987;
let (ep, _, _) = Endpoint::new()
.bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port))
.expect("Could not bind to localhost");
assert_eq!(
port,
ep.local_addr()
.expect("Could not obtain our local endpoint")
.port()
);
}
#[test]
fn echo_v6() {
run_echo(
+4
View File
@@ -57,4 +57,8 @@ impl UdpSocket {
Err(e) => Err(e),
}
}
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.io.get_ref().local_addr()
}
}