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