PHP : Send an UDP broadcast message , and wait the response
Asked Answered
S

1

11

I used this code to send an UDP broadcast message

$ip = "255.255.255.255";
$port = 8888;
$str = "DEVICE_DISCOVERY";

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); 
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); 
socket_sendto($sock, $str, strlen($str), 0, $ip, $port);

socket_recvfrom($sock, $buf, 20, 0, $ip, $port);
echo "Messagge : < $buf > , $ip : $port <br>";

socket_close($sock);

I want that some specific network devices (in my case is some Arduino boards with ethernet shield) respond with a particular message.

The code works, but in this way i can't print all the responses but only one.

Sidestep answered 7/8, 2015 at 13:22 Comment(6)
Eh, so, you mean you want to use a loop?Ha
Sure of course, but in this case i don't know how to use itSidestep
Is your return data in a array? use foreach(){}, find out what form of data your response is turned in and then use the appropriate loop.Ha
the response is a stringSidestep
Show us the string thenHa
Every device response with a string , a very simple string , like "abc" . The problem is not the type of the response , but how "listen" all the responses.Sidestep
B
9

You need a while loop, from which you break if there's no response within timeout.

First set timeout, eg 5 seconds:

socket_set_option($sock,SOL_SOCKET,SO_RCVTIMEO,array("sec"=>5,"usec"=>0));

And the loop:

while(true) {
  $ret = @socket_recvfrom($sock, $buf, 20, 0, $ip, $port);
  if($ret === false) break;
  echo "Messagge : < $buf > , $ip : $port <br>";
}

Full code:

$ip = "255.255.255.255";
$port = 8888;
$str = "DEVICE_DISCOVERY";

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); 
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));
socket_sendto($sock, $str, strlen($str), 0, $ip, $port);

while(true) {
  $ret = @socket_recvfrom($sock, $buf, 20, 0, $ip, $port);
  if($ret === false) break;
  echo "Messagge : < $buf > , $ip : $port <br>";
}

socket_close($sock);
Bugbee answered 7/8, 2015 at 14:6 Comment(3)
I had already seen this solution , would be fine if I could set these options: socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);Sidestep
You can, SO_RCVTIMEO is extra, not instead of SOL_SOCKET.Bugbee
if i do this : socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>10,"usec"=>0)); the timeout works , but not the broadcast message , if i do this : socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, array("sec"=>10,"usec"=>0)); nothing worksSidestep

© 2022 - 2024 — McMap. All rights reserved.