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.
| <?php | |
| /** | |
| * Find a free port on the system | |
| * | |
| * @return int | |
| */ | |
| function find_free_port() | |
| { | |
| $sock = socket_create_listen(0); | |
| socket_getsockname($sock, $addr, $port); | |
| socket_close($sock); | |
| return $port; | |
| } |
Thanks for this!