Skip to content

Instantly share code, notes, and snippets.

@jluims
Created July 15, 2023 00:47
Show Gist options
  • Save jluims/a02731b0a87b4cfd4cc2d6ab03f22dce to your computer and use it in GitHub Desktop.
Save jluims/a02731b0a87b4cfd4cc2d6ab03f22dce to your computer and use it in GitHub Desktop.
bedrock server list ping (python)
from dataclasses import dataclass
import socket
import random
@dataclass
class Response:
motd: str
protocol_version: str
version_name: str
online_players: int
total_players: int
server_id: str
motd_description: str
game_mode: str
game_mode_num: int
port_ipv4: int
port_ipv6: int
class Bedrock:
def __init__(self) -> None:
self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def ping(self, ip: str, port: int, timeout: int = 3):
self.client.settimeout(timeout)
# packet id: unconnected ping
packet_type = 0x01
# 8-bit timestamp, doesn't really matter
timestamp = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
# magic bytes
magic = [0x00, 0xff, 0xff, 0x00, 0xfe, 0xfe, 0xfe, 0xfe,
0xfd, 0xfd, 0xfd, 0xfd, 0x12, 0x34, 0x56, 0x78]
# guid (64-bit unique random number)
guid = random.getrandbits(64).to_bytes(8)
buf = bytes([packet_type, *timestamp, *magic, *guid])
address = (ip, port)
self.client.sendto(buf, address)
while True:
data, ip = self.client.recvfrom(4096)
if ip == address:
if data[0] != 28: # packet id: unconnected pong
print('wrong packet')
continue
# the packet id takes up one bit
# the time takes up 8 bits
# the server guid takes up 8 bits
# the magic bytes take 16 bits
# the server id takes 2 bits
offset = 1 + 8 + 8 + 16 + 2
mc_data = str(data[offset:]).split(';')
res = Response(
mc_data[1],
mc_data[2],
mc_data[3],
int(mc_data[4]),
int(mc_data[5]),
mc_data[6],
mc_data[7],
mc_data[8],
int(mc_data[9]),
int(mc_data[10]),
int(mc_data[11]))
return res
bd = Bedrock()
# Lifeboat
res = bd.ping('51.81.203.94', 19132)
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment