xref: /php-src/ext/sockets/tests/socket_icmp.phpt (revision 33ba1a4a)
1--TEST--
2socket_create with IPPROTO_ICMP
3--EXTENSIONS--
4sockets
5--SKIPIF--
6<?php
7if (!defined("IPPROTO_ICMP")) die("skip IPPROTO_ICMP not available");
8// IPPROTO_ICMP* functions with raw sockets, thus requiring administrative role.
9if (PHP_OS_FAMILY !== "Windows" && (!function_exists("posix_getuid") || posix_getuid() != 0)) die('skip IPPROTO_ICMP requires root permissions.');
10?>
11--FILE--
12<?php
13
14$host = '127.0.0.1';
15
16$type = 8;
17$code = 0;
18$identifier = 16;
19$sequence = 1;
20$data = "ECHO";
21
22$socket = socket_create(AF_INET, SOCK_RAW, IPPROTO_ICMP);
23if (!$socket) {
24    die("Unable to create socket: " . socket_strerror(socket_last_error()) . "\n");
25}
26
27$header = pack('C2n3a*', $type, $code, 0, $identifier, $sequence, $data);
28$checksum = function($header): int {
29    $bit = unpack('n*', $header);
30    $sum = array_sum($bit);
31
32    while ($sum >> 16) {
33        $sum = ($sum & 0xFFFF) + ($sum >> 16);
34    }
35    return ~ $sum & 0xFFFF;
36};
37$header = pack('C2n3a*', $type, $code, $checksum($header), $identifier, $sequence, $data);
38
39if (!socket_sendto($socket, $header, strlen($header), 0, $host, 0)) {
40    die("Unable to send packet: " . socket_strerror(socket_last_error($socket)) . "\n");
41}
42
43$read = [$socket];
44$write = $except = [];
45$timeout = ['sec' => 4, 'usec' => 0];
46if (socket_select($read, $write, $except, $timeout['sec'], $timeout['usec']) > 0) {
47    $response = '';
48    socket_recv($socket, $response, 65535, 0);
49    var_dump(bin2hex($response));
50} else {
51    die("Unable to read the response\n");
52}
53
54socket_close($socket);
55?>
56--EXPECTF--
57string(64) "%s"
58