Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class utils {
- public function sendPackets($ip, $port, $data)
- {
- $start = microtime(true);
- if(!isset($this->socket))
- {
- $this->socket = @fsockopen($ip, $port);
- stream_set_timeout($this->socket, 10);
- }
- foreach($data as $chunk)
- {
- fwrite($this->socket, $chunk);
- }
- $length = $this->readVarInt();
- while(strlen(@$response) < $length)
- {
- if(microtime(true) - $start > 10)
- return ['error', 'Сервер не ответил на запрос'];
- $remainder = $length - strlen(@$response);
- $block = fread($this->socket, $remainder);
- if(!$block)
- return ['error', 'Сервер вернул слишком мало данных.'];
- @$response .= $block;
- }
- if($response === false)
- return ['error', 'Сервер не вернул данных вообще.'];
- return substr($response, 3);
- }
- public function ping($ip, $port)
- {
- $data = "\x00\x04".pack('c', strlen($ip)).$ip.pack('n', $port)."\x01";
- $data = pack('c', strlen($data)).$data;
- $response = $this->sendPackets($ip, $port, [$data, "\x01\x00"]);
- $response = json_decode($response, true);
- if(!$response)
- return ['error', 'Сервер вернул некорректные данные.'];
- return $response['players']['online'];
- }
- public function readVarInt()
- {
- $i = 0;
- $j = 0;
- while(true)
- {
- $k = @fgetc($this->socket);
- if($k === false)
- return 0;
- $k = ord( $k );
- $i |= ($k & 0x7F) << $j++*7;
- if($j > 5)
- return ['error', 'VarInt при пинге слишком большой.'];
- if(($k & 0x80) != 128)
- break;
- }
- return $i;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement