1--TEST-- 2Test if socket_recvfrom() receives data sent by socket_sendto() via IPv4 UDP 3--EXTENSIONS-- 4sockets 5--FILE-- 6<?php 7$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); 8if (!$socket) { 9 die('Unable to create AF_INET socket'); 10} 11 12if (!socket_bind($socket, '127.0.0.1', 0)) { 13 die(sprintf( 14 'An error occurred while binding socket: %s', 15 socket_strerror(socket_last_error($socket)))); 16} 17 18socket_getsockname($socket, $address, $port); 19 20$msg = "Ping!"; 21$len = strlen($msg); 22$sent = socket_sendto($socket, $msg, $len, 0, $address, $port); 23if ($sent === false) { 24 die(sprintf( 25 'An error occurred while sending to the socket: %s', 26 socket_strerror(socket_last_error($socket)))); 27} else if ($sent != $len) { 28 die(sprintf( 29 '%d bytes have been sent instead of the %d bytes expected', 30 $sent, $len)); 31} 32 33$wants = $len; 34$recvd = 0; 35$buf = null; 36 37while ($recvd < $len) { 38 $bytes = socket_recvfrom( 39 $socket, $buffering, $wants, 0, $address, $port); 40 41 if (($bytes === false) && ($errno = socket_last_error($socket))) { 42 if ($errno = SOCKET_EAGAIN) { 43 socket_clear_error($socket); 44 continue; 45 } 46 47 die(sprintf( 48 'An error occurred while sending to the socket: %s', 49 socket_strerror($errno))); 50 } 51 52 $recvd += $bytes; 53 $wants -= $bytes; 54 $buf .= $buffering; 55} 56 57if ($recvd != $len) { 58 die(sprintf( 59 '%d bytes have been received instead of the %d bytes expected', 60 $recvd, $len)); 61} 62 63echo "Received $buf from remote address $address and remote port $port" . PHP_EOL; 64?> 65--EXPECTF-- 66Received Ping! from remote address %s and remote port %d 67