3declare(strict_types=1);
13require dirname(__DIR__) .
'/vendor/autoload.php';
15if(count($argv) === 3){
16 $broadcastAddress = $argv[1];
17 $port = (int) $argv[2];
19 echo
"Usage: php scan.php <broadcast address> <port>" . PHP_EOL;
23if(str_contains($broadcastAddress,
".")){
30$socket->enableBroadcast();
31$clientId = mt_rand(0, Limits::INT32_MAX);
32\GlobalLogger::get()->info(
"Listening on " . $bindAddress);
33\GlobalLogger::get()->info(
"Press CTRL+C to stop");
35function sendPing(
ServerSocket $socket,
string $broadcastAddress,
int $port,
int $clientId) : void{
37 $ping->clientId = $clientId;
38 $ping->sendPingTime = intdiv(hrtime(
true), 1_000_000);
41 $ping->encode($serializer);
42 $socket->writePacket($serializer->getBuffer(), $broadcastAddress, $port);
44sendPing($socket, $broadcastAddress, $port, $clientId);
46socket_set_option($socket->getSocket(), SOL_SOCKET, SO_RCVTIMEO, [
"sec" => 1,
"usec" => 0]);
49 $pong = $socket->readPacket($serverIp, $serverPort);
50 if($pong !==
null && ord($pong[0]) === MessageIdentifiers::ID_UNCONNECTED_PONG){
51 \GlobalLogger::get()->info(
"Pong received from $serverIp:$serverPort: " . $pong);
54 if($e->getCode() === SOCKET_ETIMEDOUT){
55 sendPing($socket, $broadcastAddress, $port, $clientId);