Have you ever needed to have a script check whether a Minecraft server was online, or retrieve its listing information, like the “Message of the Day” (server description) or the number of active players? Maybe you run your own server, and want to display the status on a community website. Or perhaps you have something more ambitious in mind.
After reading up on the protocol Minecraft uses for the in-game listing of your favorite servers, I put together a simple PHP class that makes it easy. Here’s a fancy demo that makes use of it.
The library, which you can download on GitHub, along with the aforementioned demo page, looks like this:
< ?php class MCServerStatus { public $server; public $online, $motd, $online_players, $max_players; public $error = "OK"; function __construct($url, $port = '25565') { $this->server = array( "url" => $url, "port" => $port ); if ( $sock = @stream_socket_client('tcp://'.$url.':'.$port, $errno, $errstr, 1) ) { $this->online = true; fwrite($sock, "\xfe"); $h = fread($sock, 2048); $h = str_replace("\x00", '', $h); $h = substr($h, 2); $data = explode("\xa7", $h); unset($h); fclose($sock); if (sizeof($data) == 3) { $this->motd = $data[0]; $this->online_players = (int) $data[1]; $this->max_players = (int) $data[2]; } else { $this->error = "Cannot retrieve server info."; } } else { $this->online = false; $this->error = "Cannot connect to server."; } } }
There are some code snippets strewn around the internet that do essentially the same thing, but without the handy wrapper class.
To query a server, you instantiate the class and pass it the IP or domain name of the server, as well as the port if it is not the default Minecraft port of 25565. (Do not include “http://” or any slashes. Just the hostname or IP.)
include "MCServerStatus.php"; $server = new MCServerStatus("s.nerd.nu", 25565); //The second argument is optional in this case
Once you have created a new instance of the object, you can use the information that it gathered.
$var = $server->online; //$server->online returns true if the server is online, and false otherwise echo $server->motd; //Outputs the Message of the Day echo $server->online_players; //Outputs the number of players online echo $server->max_players; //Outputs the maximum number of players the server allows print_r($server); //Shows an overview of the object and its contents. (For debugging.)
Now go and play some Minecraft!
Update: MCServerStatus is now on Github. Fork away!
Update 2012/11/12: The version of the library available on GitHub has been updated to work with the new protocol in Minecraft 1.4.