Skip to content

Instantly share code, notes, and snippets.

Last active January 21, 2021 17:55
What would you like to do?
Non-blocking socket connection
function nonblock_socket_connect($ip, $port)
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!socket_set_nonblock($socket)) {
$connected = @socket_connect($socket, $ip, $port);
if (!$connected) {
// If the socket is non-blocking then socket_connect() function returns FALSE with an error Operation now in progress.
$in_progress = (strpos(socket_strerror(socket_last_error()), 'in progress') !== false);
if (!$in_progress) {
return $socket;
function socket_error($socket)
$errno = socket_last_error($socket);
$errstr = socket_strerror($errno);
throw new Exception($errstr, $errno);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment