From a2438d04102e873bb6394bd1ca38448f52dd31bd Mon Sep 17 00:00:00 2001 From: Yoshua Wuyts Date: Sun, 3 Jun 2018 23:16:49 +0200 Subject: [PATCH] create .bind_or() --- src/lib.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 9606e62..f0ddce8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,4 +54,15 @@ impl Port { _ => Err(io::Error::new(io::ErrorKind::Other, "No port supplied.")), } } + + /// Create a TCP socket by calling to `.bind()`. If it fails, create a socket + /// on `port`. + /// + /// Useful to create a default socket to listen to if none was passed. + pub fn bind_or(&self, port: u16) -> std::io::Result { + match self.bind() { + Ok(listener) => Ok(listener), + Err(_) => TcpListener::bind(("127.0.0.1", port)), + } + } }