Skip to content

Commit

Permalink
feat: automatically find a free port
Browse files Browse the repository at this point in the history
  • Loading branch information
TrickyPi committed Mar 25, 2023
1 parent dd62b27 commit 5cb02ab
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/ip_port.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use std::net::{Ipv4Addr, SocketAddrV4, TcpListener};
use std::ops::Range;

type Port = u16;

pub fn get_used_port_in_tcp(range: Range<Port>) -> Option<Port> {
for port in range {
if is_free_in_tcp(port) {
return Some(port);
}
}
return None;
}

pub fn is_free_in_tcp(port: Port) -> bool {
let ipv4 = SocketAddrV4::new(create_default_ipv4(), port);
TcpListener::bind(ipv4).is_ok()
}

pub fn create_default_ipv4() -> Ipv4Addr {
Ipv4Addr::new(127, 0, 0, 1)
}
15 changes: 14 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use std::convert::Infallible;
use std::net::SocketAddr;
use std::path::PathBuf;

mod ip_port;

const NOTFOUND: &[u8] = b"Not Found";

/// host static files
Expand All @@ -31,7 +33,18 @@ async fn main() {

async fn create_server(args: Cli) {
let Cli { port, path, .. } = args;
let addr = SocketAddr::from(([127, 0, 0, 1], port));

let mut available_port = port;
if !ip_port::is_free_in_tcp(port) {
let start = 7878;
let end = 8989;
match ip_port::get_used_port_in_tcp(start..end) {
Some(port) => available_port = port,
None => panic!("the {} port is not free, chost try to find a free port from {} to {}, but also didn\'t find a free port, please use --port flag to specify a free port", port, start, end),
};
};

let addr = SocketAddr::from((ip_port::create_default_ipv4(), available_port));
let make_svc = make_service_fn(move |_| {
let path = path.clone();
async move {
Expand Down

0 comments on commit 5cb02ab

Please sign in to comment.