Skip to content

Instantly share code, notes, and snippets.

@flotwig flotwig/check.php
Last active Oct 25, 2018

Embed
What would you like to do?
Minecraft Server List Properties Example A concise, over-commented, efficiently-coded example for pinging a Minecraft server and retrieving its status. No error checking.
<?php
function pingMCServer($server,$port=25565,$timeout=2){
$socket=socket_create(AF_INET,SOCK_STREAM,getprotobyname('tcp')); // set up socket holder
socket_connect($socket,$server,$port); // connect to minecraft server on port 25565
socket_send($socket,chr(254).chr(1),2,null); // send 0xFE 01 -- tells the server we want pinglist info
socket_recv($socket,$buf,3,null); // first 3 bytes indicate the len of the reply. not necessary but i'm not one for hacky socket read loops
$buf=substr($buf,1,2); // always pads it with 0xFF to indicate an EOF message
$len=unpack('n',$buf); // gives us 1/2 the length of the reply
socket_recv($socket,$buf,$len[1]*2,null); // read $len*2 bytes and hang u[
$data=explode(chr(0).chr(0),$buf); // explode on nul-dubs
array_shift($data); // remove separator char
return $data; // boom sucka
}
@dreadiscool

This comment has been minimized.

Copy link

dreadiscool commented Jul 21, 2013

Much better than the older ping

@villermen

This comment has been minimized.

Copy link

villermen commented Oct 26, 2013

Encoding of the final strings seemed to be off (e.g. at version it said 1.6.4 but the strlen was 10) I've managed to get it to work properly by changing up the encoding of buf. It looked alright, but once you try to draw the strings with gd you'll get what I mean by it seeming off . It might be a hack but it works for me.

socket_recv($socket,$buf,$len[1]*2,null); // read $len*2 bytes and hang up
$buf = mb_convert_encoding($buf, "auto", "UTF-16BE"); //convert to encoding php can deal with
$data=explode(chr(0),$buf); // explode on nul-dubs
@Goatti

This comment has been minimized.

Copy link

Goatti commented Oct 26, 2013

How would this look for the new protocol, handshake etc in 1.7?
I would give my right arm for an updated version ;)

@Emiel45

This comment has been minimized.

Copy link

Emiel45 commented Nov 25, 2013

@timmyRS

This comment has been minimized.

Copy link

timmyRS commented Oct 25, 2018

$timeout is never used?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.