Skip to content

Instantly share code, notes, and snippets.

Last active Jul 12, 2022
What would you like to do?
Find Free Port with PHP

Find Free Port with PHP

This is a quick way to find a random free port on a system using PHP:

$port = find_free_port();

Benchmarked locally, where finding a port always took around 0.15ms.

* Find a free port on the system
* @return int
function find_free_port()
$sock = socket_create_listen(0);
socket_getsockname($sock, $addr, $port);
return $port;
Copy link

AmraniCh commented Mar 24, 2021

Thanks for this!

Copy link

vluzrmos commented May 22, 2021


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment