Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active November 2, 2023 10:22
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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;
}
@AmraniCh
Copy link

Thanks for this!

@vluzrmos
Copy link

thanks!

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