User Contributed Notes 11 notes

Took me about 20 minutes to figure out the proper arguments to supply for a AF_UNIX socket. Anything else, and I would get a PHP warning about the 'type' not being supported. I hope this saves someone else time.

Okay I talked with Richard a little (via e-mail). We agree that getprotobyname() and using the constants should be the same in functionality and speed, the use of one or the other is merely coding style. Personally, we both think the constants are prettier :).

The eight different protocols are the ones implemented in PHP- not the total number in existance (RFC 1340 has 98).

All we disagree on is using 0- Richard says that "accordning to the official unix/bsd sockets 0 is more than fine." I think that since 0 is a reserved number according to RFC 1320, and when used usually refers to IP, not one of it's sub-protocols (TCP, UDP, etc.)

Here's a ping function that uses sockets instead of exec(). Note: I was unable to get socket_create() to work without running from CLI as root. I've already calculated the package's checksum to simplify the code (the message is 'ping' but it doesn't actually matter).

It took some time to understand how one PHP process can communicate with another by means of unix udp sockets. Examples of 'server' and 'client' code are given below. Server is assumed to run before client starts.

// same socket will be later used in recv_from// no binding is required if you wish only send and never receive$client_side_sock = dirname(__FILE__)."/client.sock";if (!socket_bind($socket, $client_side_sock)) die("Unable to bind to $client_side_sock");

// use socket to send dataif (!socket_set_nonblock($socket)) die('Unable to set nonblocking mode for socket');// server side socket filename is known apriori$server_side_sock = dirname(__FILE__)."/server.sock";$msg = "Message";$len = strlen($msg);// at this point 'server' process must be running and bound to receive from serv.sock$bytes_sent = socket_sendto($socket, $msg, $len, 0, $server_side_sock);if ($bytes_sent == -1) die('An error occured while sending to the socket');else if ($bytes_sent != $len) die($bytes_sent . ' bytes have been sent instead of the ' . $len . ' bytes expected');

// append the data to the return variable // for large files this function should take a file handle as an arg$ret .= substr($buffer, 4); } while(strlen($buffer) == 516); // the first non-full packet is the last.return $ret; }?>