Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send datagrams through a unix socket from PHP?

Tags:

php

unix

sockets

I'm doing:

$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (@socket_connect($socket, $path) === false) { ... }

But I get this error:

(91): Protocol wrong type for socket

Am I using any of the parameters wrong? I suspect from the second socket_create parameter. I could't find any help in the documentation: http://php.net/manual/es/function.socket-create.php

like image 666
Juanjo Conti Avatar asked Dec 28 '22 03:12

Juanjo Conti


2 Answers

It's maby outdated, but I've found that this way it works properly:

$sock = stream_socket_client('unix:///tmp/test.sock', $errno, $errst);
fwrite($sock, 'message');
$resp = fread($sock, 4096);
fclose($sock);
like image 121
Rafał Toboła Avatar answered Jan 05 '23 19:01

Rafał Toboła


For Unix sockets we don't need to use socket_connect.

Here is a very simple working example with a sender and a receiver:

sender.php

<?php
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
socket_sendto($socket, "Hello World!", 12, 0, "/tmp/myserver.sock", 0);
echo "sent\n";
?>

receiver.php

<?php

$file = "/tmp/myserver.sock";
unlink($file);

$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);

if (socket_bind($socket, $file) === false) {
  echo "bind failed";
}

if (socket_recvfrom($socket, $buf, 64 * 1024, 0, $source) === false) {
  echo "recv_from failed";
}

echo "received: " . $buf . "\n";

?>

Note that only the receiver needs to bind to an address (the unix socket file) and then use socket_recvfrom. The sender just calls socket_sendto.

like image 34
Bernardo Ramos Avatar answered Jan 05 '23 17:01

Bernardo Ramos