Skip to content

Instantly share code, notes, and snippets.

@minecrafter
Created November 22, 2016 22:28
Show Gist options
  • Save minecrafter/5f29cff8825301e834284154a298e1c9 to your computer and use it in GitHub Desktop.
Save minecrafter/5f29cff8825301e834284154a298e1c9 to your computer and use it in GitHub Desktop.
Fully working ping library for MCPE written in Python
import random
from socket import socket, AF_INET, SOCK_DGRAM
from struct import pack
MAGIC = "\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x12\x34\x56\x78"
def get_random_long():
return random.getrandbits(48)
def get_ping_response(ip, port):
# create new UDP socket
sock = socket(AF_INET, SOCK_DGRAM)
try:
sock.settimeout(2)
# UNCONNECTED_PING
unconnected_ping = "\x01" + pack('>q', get_random_long()) + MAGIC + pack('>q', get_random_long())
sock.sendto(unconnected_ping, (ip, port))
data, addr = sock.recvfrom(2048)
# unpack the data
if data[0] != "\x1c":
raise RuntimeError("Invalid packet ID")
skip = 1 + 16 + len(MAGIC) + 2
advertise = data[skip:].split(';')
return {
"description": advertise[1],
"protocol": {
"version": advertise[3],
"id": advertise[2],
},
"players": {
"online": advertise[4],
"max": advertise[5]
}
}
finally:
sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment