文字

Socket 函数

Table of Contents

  • socket_accept — Accepts a connection on a socket
  • socket_bind — 给套接字绑定名字
  • socket_clear_error — 清除套接字或者最后的错误代码上的错误
  • socket_close — 关闭套接字资源
  • socket_cmsg_space — Calculate message buffer size
  • socket_connect — 开启一个套接字连接
  • 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 — 创建一个套接字(通讯节点)
  • 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_import_stream — Import a stream
  • 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_recv — Receives data from a connected socket
  • socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
  • socket_recvmsg — Read a message
  • 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 — Send a message
  • 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

用户评论:

[#1] paul dot hodel at gmail dot com [2011-09-10 16:39:37]

After many non-sleep nights I got the most simple multi-client server written in PHP that really works. Ctrl+C and Ctrl+V... use as command line to test it. Enjoy it.

<?php

ini_set
('error_reporting'E_ALL E_NOTICE);
ini_set('display_errors'1);

// Set time limit to indefinite execution
set_time_limit (0);

// Set the ip and port we will listen on
$address '10.203.9.67';
$port 6901;

// Create a TCP Stream socket
$sock socket_create(AF_INETSOCK_STREAM0);

// Bind the socket to an address/port
socket_bind($sock$address$port) or die('Could not bind to address');

// Start listening for connections
socket_listen($sock);

// Non block socket type
socket_set_nonblock($sock);

// Loop continuously
while (true)
{
    unset(
$read);

    
$j 0;

    if (
count($client))
    {
        foreach (
$client AS $k => $v)
        {
            
$read[$j] = $v;

            
$j++;
        }
    }

    
$client $read;

    if (
$newsock = @socket_accept($sock))
    {
        if (
is_resource($newsock))
        {
            
socket_write($newsock"$j>"2).chr(0);
            
            echo 
"New client connected $j";

            
$client[$j] = $newsock;

            
$j++;
        }
    }

    if (
count($client))
    {
        foreach (
$client AS $k => $v)
        {
            if (@
socket_recv($v$string1024MSG_DONTWAIT) === 0)
            {
                unset(
$client[$k]);

                
socket_close($v);
            }
            else
            {
                if (
$string)
                {
                    echo 
"$k$string\n";
                }
            }
        }
    }

    
//echo ".";

    
sleep(1);
}

// Close the master sockets
socket_close($sock);
?>

[#2] davidccook+php at gmail dot com [2008-08-04 21:25:36]

Planning on sending integer values through as socket, I was surprised to find PHP only supports sending strings. 
I came to the conclusion the only way to do it would be to create a string that would evaluate to the same byte values as the integer I wanted to send. So (after much messing about) I created a couple of functions: one to create this 'string' and one to convert a received value back to an integer.

<?php
//Converts an integer to 'byte array' (string), default to 4 'bytes' (chars)
function int2string($int$numbytes=4)
{
   
$str "";
   for (
$i=0$i $numbytes$i++) {
     
$str .= chr($int 256);
     
$int $int 256;
   }
   return 
$str;
}

//Converts a 'byte array' (string) to integer
function string2int($str)
{
   
$numbytes strlen($str);
   
$int 0;
   for (
$i=0$i $numbytes$i++) {
     
$int += ord($str[$i]) * pow(2$i 8);
   }
   return 
$int;
}

//Example
echo int2string(167052); // 16-bit integer converts to two bytes: 65, 65; which in turn is 'AA'
echo string2int('AA'); //back the other way
?>

[#3] firefly2442 at hotmail dot com [2008-03-29 12:31:46]

Here's a simple script for sending messages back and forth between a server and client.  At this point, the code is fairly rough because once it enters the while loop, it doesn't stop but it can be modified and fixed.  Enjoy.

<?php
//The Server
error_reporting(E_ALL);
$address "127.0.0.1";
$port "10000";
 


$mysock socket_create(AF_INETSOCK_STREAMSOL_TCP);

socket_bind($mysock$address$port);

socket_listen($mysock5);

$client socket_accept($mysock);

echo 
"Server started, accepting connections...\n";
 

$i 0;
while (
true == true)
{
    
$i++;
    echo 
"Sending $i to client.\n";
    
socket_write($client$istrlen($i));
    
    
$input socket_read($client2048);
    echo 
"Response from client is: $input\n";
    
sleep(5);
}

echo 
"Closing sockets...";
socket_close($client);

socket_close($mysock);

?>
 

<?php
//The Client
error_reporting(E_ALL);

$address "127.0.0.1";
$port 10000;


$socket socket_create(AF_INETSOCK_STREAMSOL_TCP);
if (
$socket === false) {
    echo 
"socket_create() failed: reason: " socket_strerror(socket_last_error()) . "\n";
} else {
    echo 
"socket successfully created.\n";
}

echo 
"Attempting to connect to '$address' on port '$port'...";
$result socket_connect($socket$address$port);
if (
$result === false) {
    echo 
"socket_connect() failed.\nReason: ($result) " socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo 
"successfully connected to $address.\n";
}

$i 0;
while (
true == true)
{
    
$i++;
    echo 
"Sending $i to server.\n";
    
socket_write($socket$istrlen($i));
    
    
$input socket_read($socket2048);
    echo 
"Response from server is: $input\n";
    
sleep(5);
}

echo 
"Closing socket...";
socket_close($socket);
?>

[#4] david dot schueler at tel-bilig dot de [2008-01-14 03:02:31]

NOTE! If you are trying to send a broadcast-message using this code you _may_ get a "Permission denied"-Error at socket_connect, even if you are running this as root on a linux box.
<?php
$sock 
socket_create(AF_INETSOCK_DGRAMSOL_UDP);
socket_connect($sock,"255.255.255.255"10000);
socket_set_option($sockSOL_SOCKETSO_BROADCAST1);
$buf "Hello World!";
socket_write($sock,$buf,strlen($buf));
socket_close($sock);
?>

The only workaround for this is to get the broadcast address of the interface and walk through all IPs with a for-loop.

[#5] White-Gandalf [2007-09-02 12:03:46]

At the moment (2007-09), i don't find this extension in the PECL, but instead in the usual php extension directory. It needs to be included in the php-ini:

extension = php_sockets.dll

(or ".so" - whatever for your system).

[#6] roberto at spadim dot com dot br [2007-02-11 10:27:54]

Wake on Lan , working ok without configurations, and some features

<?php
function wake_on_lan($mac,$addr=false,$port=7) {
    
//Usage
    //    $addr:
    //    You will send and broadcast tho this addres.
    //    Normaly you need to use the 255.255.255.255 adres, so i made it as default. So you don't need
    //    to do anything with this.
    //    Since 255.255.255.255 have permission denied problems you can use addr=false to get all broadcast address from ifconfig command
    //    addr can be array with broadcast IP values
    //    $mac:
    //    You will WAKE-UP this WOL-enabled computer, you need to add the MAC-addres here.
    //    Mac can be array too    
    //
    //Return
    //    TRUE:    When socked was created succesvolly and the message has been send.
    //    FALSE:    Something went wrong
    //
    //Example 1
    //    When the message has been send you will see the message "Done...."
    //    if ( wake_on_lan('00:00:00:00:00:00'))
    //        echo 'Done...';
    //    else
    //        echo 'Error while sending';
    //
    
if ($addr===false){
        
exec("ifconfig | grep Bcast | cut -d \":\" -f 3 | cut -d \" \" -f 1",$addr);
        
$addr=array_flip(array_flip($addr));
    }
    if(
is_array($addr)){
        
$last_ret=false;
        for (
$i=0;$i<count($ret);$i++)
            if (
$ret[$i]!==false)
                
$last_ret=wake_on_lan($mac,$ret[$i],$port);
        return(
$last_ret);
    }
    if (
is_array($mac)){
        
$ret=array();
        foreach(
$mac as $k=>v)
            
$ret[$k]=wake_on_lan($v,$addr,$port);
        return(
$ret);
    }
    
//Check if it's an real MAC-addres and split it into an array
    
$mac=strtoupper($mac);
    if (!
preg_match("/([A-F0-9]{1,2}[-:]){5}[A-F0-9]{1,2}/",$mac,$maccheck))
        return 
false;
    
$addr_byte preg_split("/[-:]/",$maccheck[0]);
  
    
//Creating hardware adress
    
$hw_addr '';
    for (
$a=0$a 6$a++)//Changing mac adres from HEXEDECIMAL to DECIMAL
        
$hw_addr .= chr(hexdec($addr_byte[$a]));
    
    
//Create package data
    
$msg str_repeat(chr(255),6);
    for (
$a 1$a <= 16$a++)
        
$msg .= $hw_addr;
    
//Sending data
    
if (function_exists('socket_create')){
        
//socket_create exists
        
$sock socket_create(AF_INETSOCK_DGRAMSOL_UDP);    //Can create the socket
        
if ($sock){
            
$sock_data socket_set_option($sockSOL_SOCKETSO_BROADCAST1); //Set
            
if ($sock_data){
                
$sock_data socket_sendto($sock$msgstrlen($msg), 0$addr,$port); //Send data
                
if ($sock_data){
                    
socket_close($sock); //Close socket
                    
unset($sock);
                    return(
true);
                }
            }
        }
        @
socket_close($sock);
        unset(
$sock);
    }
    
$sock=fsockopen("udp://" $addr$port);
    if(
$sock){
        
$ret=fwrite($sock,$msg);
        
fclose($sock);
    }
    if(
$ret)
        return(
true);
    return(
false);    
}
?>

[#7] aeolianmeson at NOSPAM dot blitzeclipse dot com [2006-05-30 00:13:37]

There is a fantastic book on this library called 'TCP/IP Sockets in C' (ISBN 1558608265), that covers all of the ins and outs, quirks, and everything else that goes on. It's written for C, of course, but it could have easily been written for PHP with almost no serious code differences.

Dustin

[#8] f.moisant [2006-05-18 05:41:58]

This function to send Magic Packet works really !!!


<?php
function wake($ip$mac$port
{
  
$nic fsockopen("udp://" $ip$port); 
  if(
$nic
  { 
    
$packet ""
    for(
$i 0$i 6$i++) 
       
$packet .= chr(0xFF);
    for(
$j 0$j 16$j++)
    {
      for(
$k 0$k 6$k++) 
      {
        
$str substr($mac$k 22);
        
$dec hexdec($str);
        
$packet .= chr($dec);
      }
    }
    
$ret fwrite($nic$packet);
    
fclose($nic); 
    if(
$ret)
      return 
true
  } 
  return 
false;

?>




Executed with:
wake('123.123.123.123', '112233445566', 9);

[#9] goldemish at tiscali dot it [2006-04-24 06:52:32]

Function to send Magic Packets for Wake on Wan (WOW) or Wake on Lan(WOL), without sockets library.

<?php
function WakeOnLan($ip$mac$port)
{
        
$packet "";
        for(
$i 0$i 6$i++) $packet .= chr(0xFF);
        for(
$i 0$i 6$i++) $packet .= chr((int)substr($mac$i$i 2));
        
$nic fsockopen("udp://" $ip$port));
        if(
$nic==false){
            return 
false;
            
fclose($nic);
        }
        
fwrite($nic$packet);
        
fclose($nic);
        return 
true;
}
?>

[#10] bmatheny at mobocracy dot net [2005-09-16 18:31:28]

A multicast server can be written badly as follows:

$bc_string = "Hello World!";
$sock = socket_create(AF_INET, SOCK_DGRAM, 0); 
$opt_ret = socket_set_option($sock, 1, 6, TRUE);
$send_ret = socket_sendto($sock, $bc_string, strlen($bc_string), 0, '230.0.0.1', 4446);

Checking the return types is needed, but this does allow for you to multicast from php code.

[#11] philip at birk-jensen dot dk [2005-08-22 06:22:25]

I've been using the ICMP Checksum calculation function written by Khaless [at] bigpond [dot] com. But when having an odd length of data, it failed, so I made my own instead, which adds a 0 if the data length is odd:
<?php
function icmpChecksum($data)
{
    
// Add a 0 to the end of the data, if it's an "odd length"
    
if (strlen($data)%2)
        
$data .= "\x00";
    
    
// Let PHP do all the dirty work
    
$bit unpack('n*'$data);
    
$sum array_sum($bit);
    
    
// Stolen from: Khaless [at] bigpond [dot] com
    // The code from the original ping program:
    //    sum = (sum >> 16) + (sum & 0xffff);    
    //    sum += (sum >> 16);            
    // which also works fine, but it seems to me that
    // Khaless will work on large data.
    
while ($sum>>16)
        
$sum = ($sum >> 16) + ($sum 0xffff);
    
    return 
pack('n*', ~$sum);
}
?>

[#12] aidan at php dot net [2004-08-18 05:08:08]

hexdump() is a fantastic function for "dumping" packets or binary output from servers. See the below link for more information.

http://aidanlister.com/repos/v/function.hexdump.php

[#13] noSanity [2004-05-17 19:40:04]

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_INETSOCK_RAW1);
    
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)
  {
    
// format start time
    
$start_time explode (" "$this->timer_start_time);
    
$start_time $start_time[1] + $start_time[0];
    
// get and format end time
    
$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"// the actual test data
    
$type "\x08"// 8 echo message; 0 echo reply message
    
$code "\x00"// always 0 for this program
    
$chksm "\x00\x00"// generate checksum for icmp request
    
$id "\x00\x00"// we will have to work with this later
    
$sqn "\x00\x00"// we will have to work with this later

    // now we need to change the checksum to the real checksum
    
$chksm $this->ip_checksum($type.$code.$chksm.$id.$sqn.$data);

    
// now lets build the actual icmp packet
    
$this->request $type.$code.$chksm.$id.$sqn.$data;
    
$this->request_len strlen($this->request);
  }
  
  function 
Ping($dst_addr,$timeout=5,$percision=3)
  {
    
// lets catch dumb people
    
if ((int)$timeout <= 0$timeout=5;
    if ((int)
$percision <= 0$percision=3;
    
    
// set the timeout
    
socket_set_option($this->icmp_socket,
      
SOL_SOCKET,  // socket level
      
SO_RCVTIMEO// timeout option
      
array(
       
"sec"=>$timeout// Timeout in seconds
       
"usec"=>0  // I assume timeout in microseconds
       
)
      );

    if (
$dst_addr)
    {
      if (@
socket_connect($this->icmp_socket$dst_addrNULL))
      {
      
      } 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->reply2560))
      {
        
$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

[#14] Khaless [at] bigpond [dot] com [2004-01-18 21:55:34]

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
// Computes Internet Checksum for $data
// will return a 16-bit internet checksum for $data
function inetChecksum($data)
{
    
// 32-bit accumilator, 16 bits at a time, adds odd bit on at end
    
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];
    }
    
    
// Fold 32-bit sum to 16 bits 
    
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.

[#15] murzik [at] pisem dot net [2003-10-06 04:32:25]

>The function, that send the WakeOnLan (WOL, Magic packet) signal:

<?php
# Wake on LAN - (c) HotKey (at SPR dot AT), upgraded by Murzik <tomurzik@inbox.ru>

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;

 
// send it to the broadcast address using UDP
 // SQL_BROADCAST option isn't help!!
 
$s socket_create(AF_INETSOCK_DGRAMSOL_UDP);
 if (
$s == false)
 {
  echo 
"Error creating socket!\n";
  echo 
"Error code is '".socket_last_error($s)."' - " socket_strerror(socket_last_error($s));
 }
 else
 {
 
// setting a broadcast option to socket:
  
$opt_ret =  socket_set_option($s16TRUE);
  if(
$opt_ret 0)
  {
   echo 
"setsockopt() failed, error: " strerror($opt_ret) . "\n";
  }
  
$e socket_sendto($s$msgstrlen($msg), 0$addr2050);
  
socket_close($s);
  echo 
"Magic Packet sent (".$e.") to ".$addr.", MAC=".$mac;
 }
}

#WakeOnLan('yourIPorDomain.dyndns.org', 'your:MAC:address');
#WakeOnLan('192.168.0.2', '00:30:84:2A:90:42');
#WakeOnLan('192.168.1.2', '00:05:1C:10:04:05');

//if you have switch or other routing devices in LAN, sendign to
// the local IP isn't helps! you need send to the broadcast address like this:
WakeOnLan('192.168.1.255''00:05:1C:10:04:05');

?>

[#16] talmage at usi-rpg dot com [2003-01-04 00:02:01]

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 vam@wenfreshener.com !!!!

[#17] saryon at unfix dot org [2002-07-09 09:42:03]

I found this EXTREMELY useful link on the zend php 
mailing list:

http://www.zend.com/lists/php-dev/200205/msg00286.html

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)

[#18] daniel[at]lorch.cc [2002-02-22 09:32:20]

"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.

http://www.ecst.csuchico.edu/~beej/guide/net/

[#19] judeman at yahoo dot com [2001-06-04 22:49:00]

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
// here is a basic opening of the a socket.  AF_INET specifies the internet domain.  SOCK_DGRAM 
// specifies the Datagram socket type the 0 specifies that I want to use the default protcol (which in this
// case is UDP)
$sock = socket(AF_INET, SOCK_DGRAM, 0);

// if the file handle assigned to socket is less than 0 then opening the socket failed
if($sock < 0)
{
echo "socket() failed, error: " . strerror($sock) . "\n";
}

// here's where I set the socket options, this is essential to allow broadcasting.  An earlier comment (as of 
// June 4th, 2001) explains what the parameters are.  For my purposes (UDP broadcasting) I need to set 
// the broadcast option at the socket level to true.  In C, this done using SOL_SOCKET as the level param
// (2) and SO_BROADCAST as the type param (3).  These may exist in PHP but I couldn't reference them  
// so I used the values that referencing these variables in C returns (namely 1 and 6 respectively).  This 
// function is basically just a wrapper to the C  function so check out the C documentation for more info
$opt_ret = setsockopt($sock, 1, 6, TRUE);

// if the return value is less than one, an error occured setting the options 
if($opt_ret < 0)
{
echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
}

// finally I am ready to broad cast something.  The sendto function allows this without any 
// connections (essential for broadcasting).  So, this function sends the contents of $broadcast_string to the
// general broadcast address (255.255.255.255) on port 4096.  The 0 (param 4) specifies no special
// options, you can read about the options with man sendto 
$send_ret = sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', 4096);

// if the return value is less than 0, an error has occured 
if($send_ret < 0)
{
echo "sendto() failed, error: " . strerror($send_ret) . "<BR>\n"; }
// be sure to close your socket when you're done 
close($sock);

上一篇: 下一篇: