Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active Jul 12, 2022
Embed
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.

<?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;
}
@AmraniCh
Copy link

AmraniCh commented Mar 24, 2021

Thanks for this!

@vluzrmos
Copy link

vluzrmos commented May 22, 2021

thanks!

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