Skip to content

Instantly share code, notes, and snippets.

@minecrafter
Last active April 5, 2017 09:20
Show Gist options
  • Save minecrafter/c598994290559c45f0aaea43b43410b4 to your computer and use it in GitHub Desktop.
Save minecrafter/c598994290559c45f0aaea43b43410b4 to your computer and use it in GitHub Desktop.
MCPE ping class for PHP
<?php
/**
* MIT licensed.
*/
namespace Minimum\Minecraft;
class McpePing
{
const RAKNET_MAGIC = "\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x12\x34\x56\x78";
private $description;
private $protocolVersion;
private $protocolId;
private $playersOnline;
private $playersMax;
/**
* McpePing constructor.
* @param $description
* @param $protocolVersion
* @param $protocolId
* @param $playersOnline
* @param $playersMax
*/
public function __construct($description, $protocolVersion, $protocolId, $playersOnline, $playersMax)
{
$this->description = $description;
$this->protocolVersion = $protocolVersion;
$this->protocolId = $protocolId;
$this->playersOnline = $playersOnline;
$this->playersMax = $playersMax;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @return mixed
*/
public function getProtocolVersion()
{
return $this->protocolVersion;
}
/**
* @return mixed
*/
public function getProtocolId()
{
return $this->protocolId;
}
/**
* @return mixed
*/
public function getPlayersOnline()
{
return $this->playersOnline;
}
/**
* @return mixed
*/
public function getPlayersMax()
{
return $this->playersMax;
}
public static function ping($host, $port, $timeout)
{
$stream = stream_socket_client("udp://" . $host . ":" . $port, $errno, $errstr, $timeout);
if (!$stream) {
throw new \Exception("Unable to create connection to " . $host . ":" . $port . ": " . $errstr);
}
stream_set_timeout($stream, $timeout);
stream_set_blocking($stream, TRUE);
$r1 = random_int(PHP_INT_MIN, PHP_INT_MAX);
$r2 = random_int(PHP_INT_MIN, PHP_INT_MAX);
$send = "\x01" . pack('J', $r1) . self::RAKNET_MAGIC . pack('J', $r2);
stream_socket_sendto($stream, $send);
$buf = stream_socket_recvfrom($stream, 2048);
if (count($buf) < 1 || $buf[0] != "\x1c") {
throw new \Exception("Unable to get a ping response.");
}
$ping_raw = substr($buf, strlen(self::RAKNET_MAGIC) + 19);
$ping_parts = explode(';', $ping_raw);
fclose($stream);
return new McpePing($ping_parts[1], $ping_parts[3], $ping_parts[2], $ping_parts[4], $ping_parts[5]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment