Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active May 3, 2024 06:41
Show Gist options
  • Save loilo/dbab2351e8337437cbc359cb82670a91 to your computer and use it in GitHub Desktop.
Save loilo/dbab2351e8337437cbc359cb82670a91 to your computer and use it in GitHub Desktop.
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;
}
@vluzrmos
Copy link

thanks!

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