Skip to content

Instantly share code, notes, and snippets.

@MrMicky-FR
Last active March 5, 2024 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MrMicky-FR/4b24689fb0625dd4ad6db7f7285163cc to your computer and use it in GitHub Desktop.
Save MrMicky-FR/4b24689fb0625dd4ad6db7f7285163cc to your computer and use it in GitHub Desktop.
Simple tool to ping a Minecraft server to get MOTD, online players and max players.
/*
* MIT License.
*
* Copyright (c) 2021 MrMicky
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fr.mrmicky.testproject.tools;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
/**
* Simple tool to ping a Minecraft server to get MOTD, online players and max players.
*
* @author MrMicky
*/
public class ServerPinger {
public static CompletableFuture<PingResult> ping(String address) {
return ping(address, 25565);
}
public static CompletableFuture<PingResult> ping(String address, int port) {
return ping(new InetSocketAddress(address, port), 1000);
}
public static CompletableFuture<PingResult> ping(InetSocketAddress address, int timeout) {
return CompletableFuture.supplyAsync(() -> {
try (Socket socket = new Socket()) {
socket.setSoTimeout(timeout);
socket.connect(address, timeout);
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream());
InputStream in = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_16BE)) {
out.write(new byte[]{(byte) 0xFE, 0x01});
int packetId = in.read();
int length = reader.read();
if (packetId != 0xFF) {
throw new IOException("Invalid packet id: " + packetId);
}
if (length <= 0) {
throw new IOException("Invalid length: " + length);
}
char[] chars = new char[length];
if (reader.read(chars, 0, length) != length) {
throw new IOException("Premature end of stream");
}
String string = new String(chars);
if (!string.startsWith("§")) {
throw new IOException("Unexpected response: " + string);
}
String[] data = string.split("\000");
int players = Integer.parseInt(data[4]);
int maxPlayers = Integer.parseInt(data[5]);
return new PingResult(players, maxPlayers, data[3]);
}
} catch (IOException e) {
throw new CompletionException(e);
}
});
}
public static class PingResult {
private final int players;
private final int maxPlayers;
private final String motd;
public PingResult(int players, int maxPlayers, String motd) {
this.players = players;
this.maxPlayers = maxPlayers;
this.motd = motd;
}
public int getPlayers() {
return this.players;
}
public int getMaxPlayers() {
return this.maxPlayers;
}
public String getMotd() {
return this.motd;
}
@Override
public String toString() {
return "PingResult{players=" + this.players + ", maxPlayers=" + this.maxPlayers + '}';
}
}
}

Server Pinger

Simple tool to ping a Minecraft server to get MOTD, online players and max players.

Usage

Use ServerPinger#ping, which returns a CompletableFuture<PingResult> (see CompletableFuture's JavaDoc).

Example

Non-blocking

ServerPinger.ping("funcraft.net") // The port can be specified as the second argument (25565 by default)
        .thenAccept(result -> {
            System.out.println("=== Ping result ===");
            System.out.println("Online players: " + result.getPlayers());
            System.out.println("Max players: " + result.getMaxPlayers());
            System.out.println("MOTD: " + result.getMotd());
        })
        .exceptionally(ex -> {
            ex.printStackTrace();

            return null;
        });

Blocking

try {
    ServerPinger.PingResult result = ServerPinger.ping("funcraft.net").get();

    System.out.println("=== Ping result ===");
    System.out.println("Online players: " + result.getPlayers());
    System.out.println("Max players: " + result.getMaxPlayers());
    System.out.println("MOTD: " + result.getMotd());
} catch (Exception ex) {
    ex.printStackTrace();
}

License

MIT

@Yumileashen
Copy link

how?

@HiroDeveloper
Copy link

how

@MrMicky-FR
Copy link
Author

@Yumileashen @HiroDeveloper Hi, I've updated this Gist with examples :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment