socket_create

(PHP 4 >= 4.1.0, PHP 5)

socket_create -- Create a socket (endpoint for communication)

Description

resource socket_create ( int domain, int type, int protocol )

Creates and returns a socket resource, also referred to as an endpoint of communication. A typical network connection is made up of 2 sockets, one performing the role of the client, and another performing the role of the server.

The domain parameter specifies the protocol family to be used by the socket.

表格 1. Available address/protocol families

DomainDescription
AF_INET IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family.
AF_INET6 IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family. Support added in PHP 5.0.0.
AF_UNIX Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).

The type parameter selects the type of communication to be used by the socket.

表格 2. Available socket types

TypeDescription
SOCK_STREAM Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type.
SOCK_DGRAM Supports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type.
SOCK_SEQPACKET Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call.
SOCK_RAW Provides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping, traceroute, etc).
SOCK_RDM Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.

The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.

表格 3. Common protocols

NameDescription
icmp The Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP.
udp The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead.
tcp The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission.

socket_create() Returns a socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

注: If an invalid domain or type is given, socket_create() defaults to AF_INET and SOCK_STREAM respectively and additionally emits an E_WARNING message.

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error(), and socket_strerror().


add a note add a note User Contributed Notes
jens at surefoot dot com
08-Aug-2006 08:46
Please be aware that RAW sockets (as used for the ping example) are restricted to root accounts on *nix systems. Since web servers hardly ever run as root, they won't work on webpages.

On Windows based servers it should work regardless.
07-Jan-2006 06:36
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).

<?php

function ping($host) {
  
$package = "\x08\x00\x19\x2f\x00\x00\x00\x00\x70\x69\x6e\x67";

  
/* create the socket, the last '1' denotes ICMP */   
  
$socket = socket_create(AF_INET, SOCK_RAW, 1);
  
  
/* set socket receive timeout to 1 second */
  
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));
  
  
/* connect to socket */
  
socket_connect($socket, $host, null);
  
  
/* record start time */
  
list($start_usec, $start_sec) = explode(" ", microtime());
  
$start_time = ((float) $start_usec + (float) $start_sec);
  
  
socket_send($socket, $package, strlen($package), 0);
  
   if(@
socket_read($socket, 255)) {
       list(
$end_usec, $end_sec) = explode(" ", microtime());
      
$end_time = ((float) $end_usec + (float) $end_sec);
  
      
$total_time = $end_time - $start_time;
      
       return
$total_time;
   } else {
       return
false;
   }
  
  
socket_close($socket);
}

?>
kyle gibson
29-Oct-2005 08:48
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.

<?php
$socket
= socket_create(AF_UNIX, SOCK_STREAM, 0);
// code
?>
david at eder dot us
26-Jan-2005 03:42
Sometimes when you are running CLI, you need to know your own ip address.

<?php

  $addr
= my_ip();
  echo
"my ip address is $addr\n";

  function
my_ip($dest='64.0.0.0', $port=80)
  {
  
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  
socket_connect($socket, $dest, $port);
  
socket_getsockname($socket, $addr, $port);
  
socket_close($socket);
   return
$addr;
  }
?>
david at eder dot us
08-Jun-2004 11:07
Seems there aren't any examples of UDP clients out there.  This is a tftp client.  I hope this makes someone's life easier.

<?php
 
function tftp_fetch($host, $filename)
  {
  
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

  
// create the request packet
  
$packet = chr(0) . chr(1) . $filename . chr(0) . 'octet' . chr(0);
  
// UDP is connectionless, so we just send on it.
  
socket_sendto($socket, $packet, strlen($packet), 0x100, $host, 69);

  
$buffer = '';
  
$port = '';
  
$ret = '';
   do
   {
    
// $buffer and $port both come back with information for the ack
     // 516 = 4 bytes for the header + 512 bytes of data
    
socket_recvfrom($socket, $buffer, 516, 0, $host, $port);

    
// add the block number from the data packet to the ack packet
    
$packet = chr(0) . chr(4) . substr($buffer, 2, 2);
    
// send ack
    
socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);

    
// 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;
  }
?>
evan at coeus hyphen group dot com
15-Feb-2002 10:33
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.)
email at NOSPAMrichard-samar dot de
14-Feb-2002 05:10
Actually, you don't need to use
getprotobyname("tcp") but instead can use
the constants:  SOL_TCP  and  SOL_UDP.

Here an extract of the source from
ext/sockets which should make this clear.

if ((pe = getprotobyname("tcp"))) {
       REGISTER_LONG_CONSTANT("SOL_TCP", pe->p_proto,
       CONST_CS | CONST_PERSISTENT);
}

Normally the third parameter can be set to 0. In the
original BSD Socket implementation the third parameter
(there are 8 different types, here only two) should be
IPPROTO_TCP or IPPROTO_UPD (or one of the 6 others ones).
These two parameters are though not warpped in PHP as
constants and therefore not available.
Please use SOL_TCP  and  SOL_UDP. e.g.:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

Please be aware of the fact that UDP
and TCP can only be used with AF_INET which is: "Adress Family Internet". With UNIX Domain sockets TCP/UDP would make no sense!

best regards
-Richard-Moh Samar