|
|
CVI. Socket Functions
The socket extension implements a low-level interface to the socket
communication functions based on the popular BSD sockets, providing the
possibility to act as a socket server as well as a client.
For a more generic client-side socket interface, see
stream_socket_client(),
stream_socket_server(),
fsockopen(), and
pfsockopen().
When using these functions, it is important to remember that while
many of them have identical names to their C counterparts, they
often have different declarations. Please be sure to read the
descriptions to avoid confusion.
Those unfamiliar with socket programming can find a lot
of useful material in the appropriate Unix man pages, and there is a great
deal of tutorial information on socket programming in C on the web, much
of which can be applied, with slight modifications, to socket programming
in PHP. The might be a good start.
Varov�n� | Toto roz���en� je
EXPERIMENT�LN�. Chov�n� tohoto roz���en�,
n�zvy funkc� a v�echno ostatn�, co je zde zdokumentov�no, se v budouc�ch
verz�ch PHP m��e bez ohl�en� zm�nit. Berte to v �vahu a pou��vejte tento modul
na vlastn� nebezpe��. |
Tyto funkce jsou k dispozici jako sou��st
standardn�ho modulu, kter� je v�dy dostupn�.
The socket functions described here are part of an extension to
PHP which must be enabled at compile time by giving the --enable-sockets option to
configure.
Pozn�mka: Podpora IPv6 byla p�id�na v PHP
5.0.0 .
Toto roz���en� nem� definov�no ��dn� konfigura�n�
direktivy. Toto roz���en� nem� definov�n ��dn� typ prost�edku
(resource).
Tyto konstanty jsou definov�ny t�mto roz���en�m a budou k dispozici pouze
tehdy, bylo-li roz���en� zkompilov�no spole�n� s PHP nebo dynamicky zavedeno
za b�hu.
The socket extension was written to provide a useable interface to the
powerful BSD sockets. Care has been taken that the functions work equally
well on Win32 and Unix implementations. Almost all of the sockets
functions may fail under certain conditions and therefore emit an
E_WARNING message describing the error. Sometimes this
doesn't happen to the desire of the developer. For example the function
socket_read() may suddenly emit an
E_WARNING message because the connection broke
unexpectedly. It's common to suppress the warning with the
@-operator and catch the error code within the
application with the socket_last_error() function. You
may call the socket_strerror() function with this error
code to retrieve a string describing the error. See their description for
more information.
Pozn�mka:
The E_WARNING messages generated by the socket
extension are in English though the retrieved error message will appear
depending on the current locale (LC_MESSAGES):
Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet
|
P��klad 1. Socket example: Simple TCP/IP server
This example shows a simple talkback server. Change the
address and port variables
to suit your setup and execute. You may then connect to the
server with a command similar to: telnet 192.168.1.53
10000 (where the address and port match your
setup). Anything you type will then be output on the server
side, and echoed back to you. To disconnect, enter 'quit'.
#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$address = '192.168.1.53';
$port = 10000;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
echo "socket_create() failed: reason: " . socket_strerror($sock) . "\n";
}
if (($ret = socket_bind($sock, $address, $port)) < 0) {
echo "socket_bind() failed: reason: " . socket_strerror($ret) . "\n";
}
if (($ret = socket_listen($sock, 5)) < 0) {
echo "socket_listen() failed: reason: " . socket_strerror($ret) . "\n";
}
do {
if (($msgsock = socket_accept($sock)) < 0) {
echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
break;
}
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror($ret) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "PHP: You said '$buf'.\n";
socket_write($msgsock, $talkback, strlen($talkback));
echo "$buf\n";
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>
|
|
P��klad 2. Socket example: Simple TCP/IP client
This example shows a simple, one-shot HTTP client. It simply
connects to a page, submits a HEAD request, echoes the reply,
and exits.
<?php
error_reporting(E_ALL);
echo "<h2>TCP/IP Connection</h2>\n";
$service_port = getservbyname('www', 'tcp');
$address = gethostbyname('www.example.com');
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
} else {
echo "OK.\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result < 0) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
} else {
echo "OK.\n";
}
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
echo $out;
}
echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
?>
|
|
- Obsah
- socket_accept -- Accepts a connection on a socket
- socket_bind -- Binds a name to a socket
- socket_clear_error -- Clears the error on the socket or the last error code
- socket_close -- Closes a socket resource
- socket_connect -- Initiates a connection on a socket
- socket_create_listen -- Opens a socket on port to accept connections
- socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in an array.
- socket_create -- Create a socket (endpoint for communication)
- socket_get_option -- Gets socket options for the socket
- socket_getpeername --
Queries the remote side of the given socket which may either result in host/port
or in a Unix filesystem path, dependent on its type.
- socket_getsockname --
Queries the local side of the given socket which may either result in host/port
or in a Unix filesystem path, dependent on its type.
- socket_iovec_add -- Adds a new vector to the scatter/gather array
- socket_iovec_alloc --
Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readv
- socket_iovec_delete -- Deletes a vector from an array of vectors
- socket_iovec_fetch -- Returns the data held in the iovec specified by iovec_id[iovec_position]
- socket_iovec_free -- Frees the iovec specified by iovec_id
- socket_iovec_set -- Sets the data held in iovec_id[iovec_position] to new_val
- socket_last_error -- Returns the last error on the socket
- socket_listen -- Listens for a connection on a socket
- socket_read -- Reads a maximum of length bytes from a socket
- socket_readv -- Reads from an fd, using the scatter-gather array defined by iovec_id
- socket_recv -- Receives data from a connected socket
- socket_recvfrom -- Receives data from a socket, connected or not
- socket_recvmsg -- Used to receive messages on a socket, whether connection-oriented or not
- socket_select --
Runs the select() system call on the given arrays of sockets
with a specified timeout
- socket_send -- Sends data to a connected socket
- socket_sendmsg -- Sends a message to a socket, regardless of whether it is connection-oriented or not
- socket_sendto -- Sends a message to a socket, whether it is connected or not
- socket_set_block --
Sets blocking mode on a socket resource
- socket_set_nonblock -- Sets nonblocking mode for file descriptor fd
- socket_set_option -- Sets socket options for the socket
- socket_shutdown -- Shuts down a socket for receiving, sending, or both.
- socket_strerror -- Return a string describing a socket error
- socket_write -- Write to a socket
- socket_writev -- Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id
add a note
User Contributed Notes
Socket Functions
m dot hoppe at hyperspeed dot de
03-Sep-2004 01:36
Very good step-by-step tutorial for a network daemon is here:
[next]
[before] /psecom,id,484,nodeid,114.html
Sorry, I was forced to split this link. :-(
aidan at php dot net
18-Aug-2004 12:08
hexdump() is a fantastic function for "dumping" packets or binary output from servers. See the below link for more information.
Toppi at kacke dot de
18-Jun-2004 02:06
Here another socketclass which can handle the most importand things.
Here a little Chatserver based on this class.
Maybe its helpful :)
Toppi
KnoB
11-Jun-2004 12:35
A little example that shows how to implement a simple multi-client iterative server (without forking). Launch the server and connect multiple telnet clients on it. It's a basic chat program.
#!/usr/bin/php -q
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$address = '127.0.0.1';
$port = 8888;
function handle_client($allclient, $socket, $buf, $bytes) {
foreach($allclient as $client) {
socket_write($client, "$socket wrote: $buf");
}
}
if (($master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
echo "socket_create() failed: reason: " . socket_strerror($master) . "\n";
}
socket_set_option($master, SOL_SOCKET,SO_REUSEADDR, 1);
if (($ret = socket_bind($master, $address, $port)) < 0) {
echo "socket_bind() failed: reason: " . socket_strerror($ret) . "\n";
}
if (($ret = socket_listen($master, 5)) < 0) {
echo "socket_listen() failed: reason: " . socket_strerror($ret) . "\n";
}
$read_sockets = array($master);
while (true) {
$changed_sockets = $read_sockets;
$num_changed_sockets = socket_select($changed_sockets, $write = NULL, $except = NULL, NULL);
foreach($changed_sockets as $socket) {
if ($socket == $master) {
if (($client = socket_accept($master)) < 0) {
echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
continue;
} else {
array_push($read_sockets, $client);
}
} else {
$bytes = socket_recv($socket, $buffer, 2048, 0);
if ($bytes == 0) {
$index = array_search($socket, $read_sockets);
unset($read_sockets[$index]);
socket_close($socket);
} else {
$allclients = $read_sockets;
array_shift($allclients); handle_client($allclients, $socket, $buffer, $bytes);
}
}
}
}
?>
noSanity
18-May-2004 02:40
I have searched long and hard for a ping script that does NOT use EXEC() or SYSTEM(). So far, I have found nothing, so I decided to write my own, which was a task to say the least.
First off, I would like to thank Khaless for their checksum function, converting it from C looked like a task in itself.
Here is the class I wrote
<?php
class Net_Ping
{
var $icmp_socket;
var $request;
var $request_len;
var $reply;
var $errstr;
var $time;
var $timer_start_time;
function Net_Ping()
{
$this->icmp_socket = socket_create(AF_INET, SOCK_RAW, 1);
socket_set_block($this->icmp_socket);
}
function ip_checksum($data)
{
for($i=0;$i<strlen($data);$i += 2)
{
if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
else $bits = unpack('C*',$data[$i]);
$sum += $bits[1];
}
while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
$checksum = pack('n1',~$sum);
return $checksum;
}
function start_time()
{
$this->timer_start_time = microtime();
}
function get_time($acc=2)
{
$start_time = explode (" ", $this->timer_start_time);
$start_time = $start_time[1] + $start_time[0];
$end_time = explode (" ", microtime());
$end_time = $end_time[1] + $end_time[0];
return number_format ($end_time - $start_time, $acc);
}
function Build_Packet()
{
$data = "abcdefghijklmnopqrstuvwabcdefghi"; $type = "\x08"; $code = "\x00"; $chksm = "\x00\x00"; $id = "\x00\x00"; $sqn = "\x00\x00"; $chksm = $this->ip_checksum($type.$code.$chksm.$id.$sqn.$data);
$this->request = $type.$code.$chksm.$id.$sqn.$data;
$this->request_len = strlen($this->request);
}
function Ping($dst_addr,$timeout=5,$percision=3)
{
if ((int)$timeout <= 0) $timeout=5;
if ((int)$percision <= 0) $percision=3;
socket_set_option($this->icmp_socket,
SOL_SOCKET, SO_RCVTIMEO, array(
"sec"=>$timeout, "usec"=>0 )
);
if ($dst_addr)
{
if (@socket_connect($this->icmp_socket, $dst_addr, NULL))
{
} else {
$this->errstr = "Cannot connect to $dst_addr";
return FALSE;
}
$this->Build_Packet();
$this->start_time();
socket_write($this->icmp_socket, $this->request, $this->request_len);
if (@socket_recv($this->icmp_socket, &$this->reply, 256, 0))
{
$this->time = $this->get_time($percision);
return $this->time;
} else {
$this->errstr = "Timed out";
return FALSE;
}
} else {
$this->errstr = "Destination address not specified";
return FALSE;
}
}
}
$ping = new Net_Ping;
$ping->ping("www.google.ca");
if ($ping->time)
echo "Time: ".$ping->time;
else
echo $ping->errstr;
?>
Hope this saves some troubles.
noSanity
Khaless [at] bigpond [dot] com
19-Jan-2004 05:55
I spent a while trying to use SOCK_RAW to send ICMP request packets so i could ping. This however lead me to need the internet checksum written as a php function, which was a little hard because of the way PHP handles variable types. Anyway, to save others the effort heres what i came up with, this returns Checksum for $data
<?PHP
function inetChecksum($data)
{
for($i=0;$i<strlen($data);$i += 2)
{
if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
else $bits = unpack('C*',$data[$i]);
$sum += $bits[1];
}
while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
$checksum = pack('n1',~$sum);
return $checksum;
}
?>
And with this i was able to construct a correct PING Request.
murzik [at] pisem dot net
06-Oct-2003 11:32
>The function, that send the WakeOnLan (WOL, Magic packet) signal:
<?php
flush();
function WakeOnLan($addr, $mac)
{
$addr_byte = explode(':', $mac);
$hw_addr = '';
for ($a=0; $a < 6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($s == false)
{
echo "Error creating socket!\n";
echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
}
else
{
$opt_ret = socket_set_option($s, 1, 6, TRUE);
if($opt_ret < 0)
{
echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
}
$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
socket_close($s);
echo "Magic Packet sent (".$e.") to ".$addr.", MAC=".$mac;
}
}
WakeOnLan('192.168.1.255', '00:05:1C:10:04:05');
?>
>TO "judeman at yahoo dot com":
I haven't found setsockopt() function ip PHP, I've found an equialent: socket_set_option().
bart at mediawave dot nl
06-Jan-2003 11:42
Here is a good article on some of the differences between HTTP 1.0 and HTTP 1.1.
talmage at usi-rpg dot com
04-Jan-2003 08:02
I have spent the past two days ripping out hair trying to figure out how to prevent zombie processes w/the examples above and I just happend to find this in the manual for another lanuage, felt it neccassry to port it here.
--begin copy--
van[at]webfreshener[dot]com
11-Oct-2002 02:53
Forking your PHP daemon will cause it to zombie on exit.
...or so I've seen on:
FreeBSD (PHP4.2.x)
Debian (PHP4.3.0-dev)
Darwin (PHP4.3.0-dev)
This was tested with the example code above and other scripts created for evaluation.
Seems adding <b>--enable-sigchild</b> to your configure will get rid of the problem.
Hope that saves some hair tearing :]
--end copy--
Thanks [email protected] !!!!
saryon at unfix dot org
09-Jul-2002 04:42
I found this EXTREMELY useful link on the zend php
mailing list:
It's about being able to use multiple connections
in a php socket server, WITHOUT having
to use those threads everyone seems to be
so very fond of.
works very well :)
(ps: i didn't make it, so....don't say thanks to me ;),
thank him)
daniel[at]lorch.cc
22-Feb-2002 05:32
"Beej's Guide to Network Programming" is an absolutely excellent and easy to understand tutorial to socket programming. It was written for C developers, but as the socket functions in PHP are (almost) analoguous, this should not be a problem.
davem at olsusa dot com
18-Feb-2002 02:27
Below is a simple forked daemon I wrote in PHP. I haven't seen one yet anywhere else, so I thought some people might be wondering how to do it. Execute
with php -q <file>
<?PHP
function sig_handler($signo) {
switch($signo) {
case SIGTERM:
exit;
break;
case SIGHUP:
break;
case SIGUSR1:
print "Caught SIGUSR1...\n";
break;
case SIGCHLD:
while( pcntl_waitpid(-1,$status,WNOHANG)>0 ) {
}
break;
case SIGINT:
exit;
default:
break;
}
}
function interact($sock) {
}
function become_daemon() {
$child = pcntl_fork();
if($child) {
exit; }
posix_setsid(); chdir("/");
umask(0); return posix_getpid();
}
function open_pid_file($file) {
if(file_exists($file)) {
$fp = fopen($file,"r");
$pid = fgets($fp,1024);
fclose($fp);
if(posix_kill($pid,0)) {
print "Server already running with PID: $pid\n";
exit;
}
print "Removing PID file for defunct server process $pid\n";
if(!unlink($file)) {
print "Cannot unlink PID file $file\n";
exit;
}
}
if($fp = fopen($file,"w")) {
return $fp;
} else {
print "Unable to open PID file $file for writing...\n";
exit;
}
}
function change_identity($uid,$gid) {
global $pid_file;
if(!posix_setgid($gid)) {
print "Unable to setgid to $gid!\n";
unlink($pid_file);
exit;
}
if(!posix_setuid($uid)) {
print "Unable to setuid to $uid!\n";
unlink($pid_file);
exit;
}
}
error_reporting (4);
set_time_limit (0);
ob_implicit_flush ();
$pid_file = '/tmp/php_daemon.pid';
$underpriv_uid = '99'; $underpriv_gid = '99';
$port = 10000;
$address = 0; $quit = 0;
pcntl_signal(SIGCHLD, "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGINT, "sig_handler");
$fh = open_pid_file($pid_file);
if (($sock = socket_create (AF_INET, SOCK_STREAM, 0)) < 0) {
print "socket_create() failed: reason: " . socket_strerror ($sock) . "\n";
}
if (($ret = socket_bind ($sock, $address, $port)) < 0) {
print "socket_bind() failed: reason: " . socket_strerror ($ret) . "\n";
}
if (($ret = socket_listen ($sock, 0)) < 0) {
print "socket_listen() failed: reason: " . socket_strerror ($ret) . "\n";
}
change_identity($underpriv_uid,$underpriv_gid);
print "Server ready. Waiting for connections.....\n";
$pid = become_daemon();
fputs($fh,$pid);
fclose($fh);
while(!$quit) {
if (($connection = socket_accept($sock)) < 0) {
next;
}
if( ($child = pcntl_fork()) == -1 ) {
print "Could not fork!!\n";
print "Dying...\n";
$quit++;
}
elseif($child == 0) {
socket_close($sock);
interact($connection);
exit;
}
socket_close($connection);
}
if(posix_getpid() == $pid) {
unlink($pid_file);
}
judeman at yahoo dot com
05-Jun-2001 05:49
After several hours of working with sockets in an attempt to do UDP broadcasting, I thought a little help was in order for anyone else looking to do something similar, since it uses a number of those "undocumented" functions. Here's how I did it:
<?php
$sock = socket(AF_INET, SOCK_DGRAM, 0);
if($sock < 0)
{
echo "socket() failed, error: " . strerror($sock) . "\n";
}
$opt_ret = setsockopt($sock, 1, 6, TRUE);
if($opt_ret < 0)
{
echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
}
$send_ret = sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', 4096);
if($send_ret < 0)
{
echo "sendto() failed, error: " . strerror($send_ret) . "<BR>\n"; }
close($sock);
| |