VintageBigBlue.org

 
A PHP Multicast Datagram Example

Nov 14, 2018

The internet seems to be missing a complete and working example of how to code a PHP multicast server and clients so here it is. If you run any of these back to back and get a message about "address already in use" or related, remember the TIME_WAIT that occurs when you close a socket. It is OS dependent but a common default is 60 seconds. The group address is in the range 224.0.0.0 to 239.255.255.255. These addreses are the only ones valid for multicast use. More information on group address can be found in RFC 5771. Since you have to bind the client to an address and port you can only have one client running on a particular computer. An important fact to note is that multicast packets will not survive a trip thru any router. The router will discard them. They will go thru a switch however.

The Clients


   $len = 80 ;
   $flags = 0 ;
   $from = "" ;
   $port = 14446 ;
   $grpparms = array("group"=>"228.5.6.7","interface"=>"eth0") ;
   $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
   socket_bind($sock,'0.0.0.0',$port);
   socket_set_option($sock,IPPROTO_IP,MCAST_JOIN_GROUP,grpparms);
   socket_recvfrom($sock,$recvStr,$len,$flags,$from,$port);
   echo "Received " . $recvStr . " from " . $from ; 
   socket_close($sock) ;

The Server


   $port = 14446 ;
   $grpparms = array("group"=>"228.5.6.7","interface"=>"eth0") ;
   $mesg = "Eh, Whats up doc?" ;
   $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
   socket_set_option($sock,IPPROTO_IP,MCAST_JOIN_GROUP,$grpparms);
   socket_sendto($sock, $mesg, strlen($broadcast_string), 0, '228.5.6.7',$port);
   socket_close($sock) ; 


Contact Us
This Site's Privacy Policy
Google's privacy policies