LonghornPHP 2026

Voting

: six plus one?
(Example: nine)

The Note You're Voting On

judeman at yahoo dot com
25 years ago
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);

<< Back to user notes page

To Top