I have a device I need to talk to via UDP from within PHP (although it feels like my problem here is a Linux one not a PHP one as everything is being done at the socket level anyway).
I am sending a request to an Ethernet module in a PLC, and if I get the addressing wrong in my request then I get an error response back from the PLC as expected (by which I mean a 22 byte message sent via UDP containing the relevant error code) - I see this in my PHP code and in a Windows (Winsock-based) app I have that lets me send test queries and see the responses.
However, when I get my addressing correct, whilst the Windows app gives me the response associated with the request I made, in my PHP/Linux code I just get no response (my code hangs up waiting).
The PHP code I'm struggling with is: // Create a socket $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); // Build the message $msg = hex2str('80 00 02 00 01 00 00 11 00 00 05 01'); // Send the message socket_sendto($socket, $msg, strlen($msg), 0, '192.168.251.132', '9600'); // Get the response - this line never returns socket_recvfrom($socket, &$buf, /*Max response length*/250, /*Flags*/0, &$ip, &$port);
I would guess that the Ethernet module in the PLC either responds immediately with a response to tell me I have the address wrong, or else has to go off and collect some data before sending it back, although the time this takes is milliseconds.
If I set Flags to MSG_DONTWAIT the code no longer hangs; it just returns no characters, even if I put a delay of a couple of seconds before the function call. I'm pretty sure that the key to the solution lies in getting the flags right but there I'm stumped due to lack of knowledge (and everywhere I can find sample code the above works fine). The list of possible flags is in the PHP docs[1] but I think a fuller list would be those listed in "man 2 recv"
Any suggestions?
[1]http://www.php.net/manual/en/function.socket-recvfrom.php