Skip to main content

Mountain/IPC/WindServiceHandlers/NativeHost/
FindFreePort.rs

1#![allow(non_snake_case, unused_variables, dead_code, unused_imports)]
2
3//! Wire method: `nativeHost:findFreePort`.
4//! Scans 100 ports starting from `Arguments[0]` (default 9000) and returns the
5//! first free one. Returns 0 when nothing is free in-range so callers can
6//! distinguish "search exhausted" from a genuine port 0.
7
8use serde_json::{Value, json};
9
10pub async fn NativeFindFreePort(Arguments:Vec<Value>) -> Result<Value, String> {
11	let StartPort = Arguments.get(0).and_then(|V| V.as_u64()).unwrap_or(9000) as u16;
12
13	for Port in StartPort..StartPort + 100 {
14		if std::net::TcpListener::bind(("127.0.0.1", Port)).is_ok() {
15			return Ok(json!(Port));
16		}
17	}
18	Ok(json!(0))
19}