From e468390802acffee78d73e6376f43e0e9a4bcfbd Mon Sep 17 00:00:00 2001 From: ustulation Date: Tue, 19 Mar 2019 16:53:38 +0000 Subject: [PATCH] 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. --- quinn/src/lib.rs | 5 +++++ quinn/src/tests.rs | 14 ++++++++++++++ quinn/src/udp.rs | 4 ++++ 3 files changed, 23 insertions(+) diff --git a/quinn/src/lib.rs b/quinn/src/lib.rs index f7170ba02..8673e06b5 100644 --- a/quinn/src/lib.rs +++ b/quinn/src/lib.rs @@ -171,6 +171,11 @@ impl Endpoint { Ok(()) } + /// Get the local endpoint the underlying socket is bound to + pub fn local_addr(&self) -> io::Result { + self.inner.borrow().socket.local_addr() + } + /* /// Connect to a remote endpoint, with support for transmitting data before the connection is /// established diff --git a/quinn/src/tests.rs b/quinn/src/tests.rs index 54316a9ea..a68c33a35 100644 --- a/quinn/src/tests.rs +++ b/quinn/src/tests.rs @@ -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( diff --git a/quinn/src/udp.rs b/quinn/src/udp.rs index 7d02ef2be..5ab5ea132 100644 --- a/quinn/src/udp.rs +++ b/quinn/src/udp.rs @@ -57,4 +57,8 @@ impl UdpSocket { Err(e) => Err(e), } } + + pub fn local_addr(&self) -> io::Result { + self.io.get_ref().local_addr() + } }