4

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

4 Answers 4

7

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

check this another answer for working examples in php and C
0

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

3 Comments

With the name of the protocol you want to use, I guess. In a comment on the english doc page is a list of them: nl3.php.net/manual/en/function.getprotobyname.php
I tried "udp", which is the one I want, but got [93]: Protocol not supported.
Hmm. Is everything included in php.ini? Also, I read somewhere that udp doesn't work with ipv6, but that's probably not it. Anyway, there are some more examples here: php.net/manual/en/function.socket-create.php.
-1

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.

1 Comment

No, the reason is because it should not use socket_connect on a SOCK_DGRAM socket. And your AF_INET does not relate to the question on unix domain sockets

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.