Home > Software engineering >  PHP socket_create / socket_bind with Unix domain sockets - error address already in use
PHP socket_create / socket_bind with Unix domain sockets - error address already in use

Time:02-23

I am posting this as I've spent a few hours debugging this.

If you use socket_create / socket_bind with Unix domain sockets, then using socket_close at the end is not sufficient. You will get "address already in use" the second time you run your script. Call unlink on the file that is used for Unix domain sockets, preferably before you start to create the socket.

<?php

$socket_file = "./test.sock";

if (file_exists($socket_file))
        unlink($socket_file);
# optional file lock
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
# ... socket_set_option ...
socket_bind($socket, $socket_file);
# ...
socket_close($socket);
# optional : release lock
unlink($socket_file);

?>

Regards

CodePudding user response:

$socket_file = "./test.sock";

if (file_exists($socket_file)) unlink($socket_file);

CodePudding user response:

You can use socket_set_option() to specify that you want to reuse address and port:

socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);

See the list of options.

  • Related