Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change server behavior when port by local is set to 0 #28

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,28 @@ impl Server {
}
}

/// Create new TcpListener and return it, if port is set to 0 then in sequence search for unused port in range
async fn create_listener(port: u16, min_port: u16) -> Option<TcpListener> {
if port == 0 {
for port in min_port..65535 {
match TcpListener::bind(("0.0.0.0", port)).await {
Ok(l) => return Some(l),
Err(_) => continue,
}
}
// Check the last port as loop does not include it
match TcpListener::bind(("0.0.0.0", 65535)).await {
Ok(l) => Some(l),
Err(_) => None,
}
} else {
match TcpListener::bind(("0.0.0.0", port)).await {
Ok(l) => Some(l),
Err(_) => None,
}
}
}

async fn handle_connection(&self, stream: TcpStream) -> Result<()> {
let mut stream = Delimited::new(stream);
if let Some(auth) = &self.auth {
Expand All @@ -82,9 +104,9 @@ impl Server {
return Ok(());
}
info!(?port, "new client");
let listener = match TcpListener::bind(("0.0.0.0", port)).await {
Ok(listener) => listener,
Err(_) => {
let listener = match Server::create_listener(port, self.min_port).await {
Some(listener) => listener,
None => {
warn!(?port, "could not bind to local port");
stream
.send(ServerMessage::Error("port already in use".into()))
Expand Down