-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: automatically find a free port
- Loading branch information
Showing
2 changed files
with
36 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters