findFreePort

fun findFreePort(preferredPort: Int): Int

Finds a free TCP port starting from preferredPort. Probes upward (up to 20 attempts) until an available port is found. Falls back to an OS-assigned ephemeral port if all probed ports are busy.

TOCTOU note: There is an inherent race between closing the probe socket and the child process binding to the port. SO_REUSEADDR is set to minimize the window. llama-server does not support port-0 allocation, so this probe-then-bind approach is the best available option.

Return

An available TCP port.

Parameters

preferredPort

The first port to try.