PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<snmpwalkoidsocket_accept>
view the version of this page
Last updated: Thu, 21 Aug 2003

XCIX. Socket functions

Introduction

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 UNIX Socket FAQ might be a good start.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

Requirements

No external libraries are needed to build this extension.

Installation

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.

Note: IPv6 Support was added with PHP 5.0.0 .

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension has no resource types defined.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

AF_UNIX (integer)

AF_INET (integer)

AF_INET6 (integer)

SOCK_STREAM (integer)

SOCK_DGRAM (integer)

SOCK_RAW (integer)

SOCK_SEQPACKET (integer)

SOCK_RDM (integer)

MSG_OOB (integer)

MSG_WAITALL (integer)

MSG_PEEK (integer)

MSG_DONTROUTE (integer)

SO_DEBUG (integer)

SO_REUSEADDR (integer)

SO_KEEPALIVE (integer)

SO_DONTROUTE (integer)

SO_LINGER (integer)

SO_BROADCAST (integer)

SO_OOBINLINE (integer)

SO_SNDBUF (integer)

SO_RCVBUF (integer)

SO_SNDLOWAT (integer)

SO_RCVLOWAT (integer)

SO_SNDTIMEO (integer)

SO_RCVTIMEO (integer)

SO_TYPE (integer)

SO_ERROR (integer)

SOL_SOCKET (integer)

PHP_NORMAL_READ (integer)

PHP_BINARY_READ (integer)

SOL_TCP (integer)

SOL_UDP (integer)

Socket Errors

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.

Note: 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

Examples

Example 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);

/* Allow the script to hang around waiting for connections. */
set_time_limit (0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush ();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create (AF_INET, SOCK_STREAM, 0)) < 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;
    }
    /* Send instructions. */
    $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);
?>

Example 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";

/* 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_INET, SOCK_STREAM, 0);
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.0\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";
?>

Table of Contents
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 fds.
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 add a note User Contributed Notes
Socket functions
paul at chaos-studio dot com
07-Oct-2003 04:20
just a note on the talk back server, the remake doesn't send anything back to server like the original one does (even though i couldn't get the original one to work)

add an extra if statment to return the text:

if ($cmd != '')
{
    echo "$cmd\n";
}
murzik [at] pisem dot net
06-Oct-2003 06:32
>The function, that send the WakeOnLan (WOL, Magic packet) signal:

<?php
# Wake on LAN - (c) HotKey@spr.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');

?>

>TO "judeman at yahoo dot com":
I haven't found setsockopt() function ip PHP, I've found an equialent: socket_set_option().
K_[nospaamatall]JR at sol dot dk
25-Aug-2003 08:42
The 'simple talkback server' didnt work for me, so I re-made it.
Still simple, and it works. There must be more beginners out there
that could use this :)

My config:
WinXP Pro + Apache 2.0.46 + PHP 4.3.2 + Zend Engine v1.3.0

<?php
error_reporting 
(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit (0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush ();

$address '0.0.0.0';
$port 10000;

if ((
$sock socket_create(AF_INETSOCK_STREAM0)) === false)
{
    echo 
"socket_create() failed: reason: " socket_strerror($sock) . "\n";
}

if ((
$ret socket_bind($sock$address$port)) === false)
{
    echo 
"socket_bind() failed: reason: " socket_strerror($ret) . "\n";
}

if ((
$ret socket_listen($sock10)) === false)
{
    echo 
"socket_listen() failed: reason: " socket_strerror($ret) . "\n";
}

do
{
    if ((
$msgsock socket_accept($sock)) === false)
    {
        echo 
"socket_accept() failed: reason: " socket_strerror($msgsock) . "\n";
        break;
    }

   
/* Send instructions. */
   
$msg "\n Welcome to the PHP Test Server. \n\r" .
       
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n\r";

   
socket_write($msgsock$msgstrlen($msg));

   
$cmd "";

    do {
        if (
false === ($buf socket_read($msgsock4096)))
        {
            echo 
"socket_read() failed: reason: " socket_strerror($ret) . "\n";
            break 
2;
        }

        if (
$buf == "\r\n")
        {
            if (
$cmd == 'm00')
            {
               
socket_write($msgsock"PHP replies: Must be a cow out there...\n\r"strlen ("PHP replies: Must be a cow out there...  "));
            }
            if (
$cmd == 'quit')
            {
               
socket_write($msgsock"\n\rClosing connection ..."strlen ("  Closing connection ..."));
                break;
            }
            if (
$cmd == 'shutdown')
            {
               
socket_write($msgsock"\n\rShutdown initiated..."strlen ("  Shutdown initiated..."));
               
socket_close ($msgsock);
                break 
2;
            }
           
$cmd "";
        }
        else
        {
           
$cmd .= $buf;
        }
    } while (
true);
   
socket_close ($msgsock);
} while (
true);

socket_close ($sock);
?>
Benjamin Kuz
17-Mar-2003 06:46
The talkback example shown on this page has an error, and may not function as intended on newer versions of PHP.

the line that contains

if (FALSE === ($buf = socket_read ($msgsock, 2048))) {

needs to be

if (FALSE === ($buf = socket_read ($msgsock, 2048, PHP_NORMAL_READ))) {

This is due to changes in how PHP starts socket_read(), and may be confusing to people trying to use the example.

The way it is, it appears that the socket_read() function is executed as quickly as possible returning whatever is in it's buffer before an entire line can be sent.  Adding PHP_NORMAL_READ makes it so that the buffer isn't returned until either the buffer length is reached, or a linefeed is sent.
bart at mediawave dot nl
06-Jan-2003 07:42
Here is a good article on some of the differences between HTTP 1.0 and HTTP 1.1.

http://wireless.java.sun.com/midp/questions/chunking/
talmage at usi-rpg dot com
04-Jan-2003 04: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 vam@wenfreshener.com !!!!
gv (at) damnsw (dot) net
21-Sep-2002 04:18
#!/usr/bin/php -q
<?php
   
/*    This is a remake of a simple, one-shot HTTP client which is more or less
        nonfunctional with the current PHP sockets implementation.  The original
        can currently be found in the 'examples' section of the main sockets
        documentation -- http://http://www.php.net/manual/en/ref.sockets.php
 
        Use by `chmod 755`'ing it, then running in the command line: ./thisfile.php

        This example requires the sockets extension compiled into the PHP
        Commandline Module (http://www.php.net/manual/en/features.commandline.php)
        to run without modification.  It can, theoretically, be used with the web
        service module (Remove the "#!/usr/bin/php -q" line), but that would reduce
        the already minimal functional use to about nill.  Of course, it will
        function as an example of working sockets regardless. */

   
error_reporting (E_ALL);

   
/* Get the port for the WWW service.  This could be prevented by just using
        '80' in the socket_connect() call, but this is a slightly more
        human-readable method, or something. */
   
$service_port getservbyname"www""tcp" );

   
/* This part is actually rather important -- socket_connect() takes an IP, not
        a hostname. */
   
$address gethostbyname"www.example.com" );
   
   
/* Create a TCP/IP socket. */
   
$socket socket_createAF_INETSOCK_STREAM);
    if( 
$socket ) {
        echo 
"socket_create() failed: reason: " socket_strerror$socket ) . "\n";
        exit; 
/* There's no reason to continue to execute the script -- adding
                intelligent retry code would be beyond the scope of the
                original example. */
   
}

   
/* Attempt to connect to $address on $service_port */
   
if( !( @socket_connect$socket$address$service_port ) ) ) {
       
/*    Print an error message if the socket failed to connect; supress PHP's
            builtin error message. */
       
$result socket_last_error$socket );
       
socket_clear_error$socket );
        print 
"Error connecting to $ip:$port -- " socket_strerror$result ) . " ($result)\n";
        exit; 
/* Once again, we're not going to bother retrying. */
   
}
   
   
   
$in "GET / HTTP/1.0\r\n\r\n";
   
$out '';

   
/* Send the request for data. */
   
socket_write$socket$instrlen$in ) );

   
/* Read data. */
   
while( ($out socket_read$socket2048PHP_BINARY_READ ) ) != false ) {
       
/*    As can be seen in the socket_read() documentation, the optional "type"
            (in this case, PHP_BINARY_READ) determines when socket_read() stops
            reading.  The binary read type will read until there's no more data
            or the limit has been reached -- PHP_NORMAL_READ will stop at \r or
            \n.
           
            Doing a normal read in this situation would complicate matters
            because we'd need to re-add the line breaks.  While that may sound
            easy, correctly guessing if we're at the end of the line or we're
            just seeing the read limit kicking in would be a little iffy. 
           
            Besides, there are no disadvantages to the binary read. */
       
echo $out;
    }

   
/*    Theoretically, the webserver has already closed the socket, as it has
        finished sending data.  However, it doesn't hurt to socket_close(), as
        it does deallocational stuff that will not happen automagically when
        the remote side dies.  Presumably, PHP will do this anyway when the
        script ends, but it doesn't hurt. */
   
socket_close$socket );
 
 
/* *sniffle* My poor, innocent indenting.  Waah.
    A better formatted copy can be found here: http://www.yghe.net/~skunks/sockets.phps
  */ 

?>
saryon at unfix dot org
09-Jul-2002 11:42
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)
sethmail at poczta dot fm
08-Jul-2002 06:03
To Ramar: All you have to do is to use fopen() function.

Here is an example of using POST method:
$host = "www.php.net";
$data = "lang=en_US&pattern=sockets&show=quickref";

$fp = fsockopen($host,80);

fputs($fp, "POST /search.php HTTP/1.1\n");
fputs($fp, "Host: $host\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
fputs($fp, "Content-length: " . strlen($data) . "\n");
fputs($fp, "User-Agent: MSIE\n");
fputs($fp, "Connection: close\n\n");
fputs($fp, $data);

while (!feof($fp))
$buf .= fgets($fp,128);
fclose($fp);

echo $buf;
Pieter
10-Apr-2002 04:03
On Windows it's also possible to use sockets

Just open your PHP.ini and look for the following part:

;extension=extensions\php_sockets.dll

Unmark it like this

extension=extensions\php_sockets.dll

and there's Sockets to be build in your programs
daniel[at]lorch.cc
23-Feb-2002 01: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.

http://www.ecst.csuchico.edu/~beej/guide/net/
davem at olsusa dot com
18-Feb-2002 10: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

/*

    PHP forked daemon
    Standalone PHP binary must be compiled with --enable-sockets and --enable-pcntl
    Dave M. -2002
        Online Services USA
*/

function sig_handler($signo) {

     switch(
$signo) {
         case 
SIGTERM:
             
// handle shutdown tasks
             
exit;
             break;
         case 
SIGHUP:
             
// handle restart tasks
             
break;
         case 
SIGUSR1:
             print 
"Caught SIGUSR1...\n";
             break;
         case 
SIGCHLD:
             while( 
pcntl_waitpid(-1,$status,WNOHANG)>) { 
             }
             break;
         case 
SIGINT:
        exit;
         default:
             
// not implemented yet...
             
break;
     }

}

function 
interact($sock) {

   
// Custom code goes here... e.g: socket_read() socket_write()...

}

function 
become_daemon() {

   
$child pcntl_fork();
    if(
$child) {
        exit; 
// kill parent
   
}
   
posix_setsid(); // become session leader
   
chdir("/");
   
umask(0); // clear umask
   
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'// uid 99 == user nobody, at least on my system.
$underpriv_gid '99';

$port 10000;
$address 0// 0 binds to all addresses, may not work on fbsd

$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_INETSOCK_STREAM0)) < 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 ($sock0)) < 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()) == -) {
        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 12: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
   
// 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_INETSOCK_DGRAM0);

   
// 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($sock16TRUE);

   
// 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_stringstrlen($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);

<snmpwalkoidsocket_accept>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST