Skip to main content

Mountain/IPC/WindServiceHandlers/NativeHost/
FindFreePort.rs

1//! Wire method: `nativeHost:findFreePort`.
2//! Scans 100 ports starting from `Arguments[0]` (default 9000) and returns the
3//! first free one. Returns 0 when nothing is free in-range so callers can
4//! distinguish "search exhausted" from a genuine port 0.
5
6use serde_json::{Value, json};
7
8use crate::IPC::WindServiceHandlers::Utilities::JsonValueHelpers::arg_u64_or;
9
10pub async fn Fn(Arguments:Vec<Value>) -> Result<Value, String> {
11	let StartPort = arg_u64_or(&Arguments, 0, 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
19	Ok(json!(0))
20}