Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Socket Functions : socket_create

socket_create

Create a socket (endpoint for communication) (PHP 4 >= 4.0.7, PHP 5)
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.

Parameters

domain

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

Table 293. Available address/protocol families

Domain Description
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).


type

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

Table 294. Available socket types

Type Description
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.


protocol

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.

Table 295. Common protocols

Name Description
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.


Return Values

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.

Errors/Exceptions

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.

Examples ( Source code ) » socket_create

<?php
error_reporting
(E_ALL);

echo 
"<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port getservbyname('www''tcp');

/* Get the IP address for the target host. */
$address gethostbyname('www.example.com');

/* Create a TCP/IP socket. */
$socket socket_create(AF_INETSOCK_STREAMSOL_TCP);
if (
$socket === false) {
   echo 
"socket_create() failed: reason: " socket_strerror(socket_last_error()) . "\n";
} else {
   echo 
"OK.\n";
}

echo 
"Attempting to connect to '$address' on port '$service_port'...";
$result socket_connect($socket$address$service_port);
if (
$result === false) {
   echo 
"socket_connect() failed.\nReason: ($result) " socket_strerror(socket_last_error($socket)) . "\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$instrlen($in));
echo 
"OK.\n";

echo 
"Reading response:\n\n";
while (
$out socket_read($socket2048)) {
   echo 
$out;
}

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

Code Examples / Notes » socket_create

matth ingersoll

When running these types of sockets, typically you need to be root or else they fail (not the case with stream sockets: http://us.php.net/manual/en/function.stream-socket-server.php)
This is an example for Linux/Unix type systems to use sockets without being root. (tested on Debian and CentOS)
<?php
$user = "daemon";
$script_name = "uid"; //the name of this script
/////////////////////////////////////////////
//try creating a socket as a user other than root
echo "\n__________________________________________\n";
echo "Trying to start a socket as user $user\n";
$uid_name = posix_getpwnam($user);
$uid_name = $uid_name['uid'];
if(posix_seteuid($uid_name))
{
       echo "SUCCESS: You are now $user!\n";
       if($socket = @socket_create(AF_INET, SOCK_RAW, 1))
       {
               echo "SUCCESS: You are NOT root and created a socket! This should not happen!\n";
       } else {
               echo "ERROR: socket_create() failed because you're not root!\n";
       }
       $show_process = shell_exec("ps aux | grep -v grep | grep $script_name");
       echo "Current process stats::-->\t $show_process";
} else {
       exit("ERROR: seteuid($uid_name) failed!\n");
}
/////////////////////////////////////////////
//no try creating a socket as root
echo "\n__________________________________________\n";
echo "Trying to start a socket as user 'root'\n";
if(posix_seteuid(0))
{
       echo "SUCCESS: You are now root!\n";
       $show_process = shell_exec("ps aux | grep -v grep | grep $script_name");
       echo "Current process stats::-->\t $show_process";
       if($socket = @socket_create(AF_INET, SOCK_RAW, 1))
       {
               echo "SUCCESS: You created a socket as root and now should seteuid() to another user\n";
               /////////////////////////////////////////
               //now modify the socket as another user
               echo "\n__________________________________________\n";
               echo "Switching to user $user\n";
               if(posix_seteuid($uid_name))
               {
                       echo "SUCCESS: You are now $user!\n";
                       if(socket_bind($socket, 0, 8000))
                       {
                               echo "SUCCESS: socket_bind() worked as $user!\n";
                       } else {
                               echo "ERROR: Must be root to user socket_bind()\n";
                       }
                       $show_process = shell_exec("ps aux | grep -v grep | grep $script_name");
                       echo "Current process stats::-->\t $show_process";
                       socket_close($socket); //hard to error check but it does close as this user
                       echo "SUCCESS: You closed the socket as user $user!\n";
               } else {
                       echo "ERROR: seteuid($uid_name) failed while socket was open!\n";
               }
       } else {
               echo "ERROR: Socket failed for some reason!\n";
       }
} else {
       exit("ERROR: Changing to root failed!\n");
}
?>


kyle gibson

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
?>


ionic

To david _at* eder #do; us:
Dependent on your system, you could, at least on LINUX, use exec with "/sbin/ifconfig eth0 | awk '/inet /{ print substr($2,9) }'" (also working for non-root users), that will work a little bit faster as your PHP function.
Though, we should keep in mind that users with safe_mode enabled are more or less forced to use the socket thing. :)


david

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;
 }
?>


jens

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.


evan

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


06-jan-2006 10: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);
}
?>


email

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


Change Language


Follow Navioo On Twitter
socket_accept
socket_bind
socket_clear_error
socket_close
socket_connect
socket_create_listen
socket_create_pair
socket_create
socket_get_option
socket_getpeername
socket_getsockname
socket_last_error
socket_listen
socket_read
socket_recv
socket_recvfrom
socket_select
socket_send
socket_sendto
socket_set_block
socket_set_nonblock
socket_set_option
socket_shutdown
socket_strerror
socket_write
eXTReMe Tracker