Juanjo Conti
Juanjo Conti

Reputation: 30013

How to send datagrams through a unix socket from PHP?

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

Upvotes: 4

Views: 10421

Answers (4)

Bernardo Ramos
Bernardo Ramos

Reputation: 4577

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.

Upvotes: 4

iccle
iccle

Reputation: 67

The third argument to socket_create is incorrect hence the error message.

It should be socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

The value 0 that you specified corresponds to SOL_IP which is not a supported protocol in php.

Upvotes: -1

Rafał Toboła
Rafał Toboła

Reputation: 376

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);

Upvotes: 7

Spiny Norman
Spiny Norman

Reputation: 8327

Have you tried using getprotobyname() for the 3rd (protocol) parameter?

Upvotes: 0

Related Questions