Created
April 4, 2026 19:07
-
-
Save crischutu07/fc722a0dd84ebe5ca7f8cb60d105395c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # mcping - Minecraft server ping written in Bash | |
| # This Bash script uses only `netcat` to ping a Minecraft server. (because my device doesn't support /dev/tcp) | |
| # Unfortunately, netcat is not capable of closing TCP connection when it recieves the data from the server | |
| # so either you Ctrl-C this script or wait for 30 seconds until netcat automatically end itself. (because of "timed out") | |
| # Author: Nguyen Hong Son <cris@crischu07.is-a.dev> | |
| if [ -z "$@" ]; then | |
| echo "Usage: $0 [<address>] <port> <version>" | |
| exit 2 | |
| fi | |
| ADDR="$1" | |
| if [ ! -z "$2" ]; then | |
| PORT="$2" | |
| else | |
| PORT=25565 | |
| fi | |
| if [ ! -z "$3" ]; then | |
| VERSION="$3" | |
| else | |
| VERSION="-1" | |
| fi | |
| varint_encode() { | |
| local value=$1 | |
| # handle overflow on negative number | |
| if (( value < 0 )); then | |
| value=$(( value & 0xFFFFFFFF )) | |
| fi | |
| while true; do | |
| local byte=$(( value & 0x7F )) | |
| value=$(( value >> 7 )) | |
| if [ $value -ne 0 ]; then | |
| byte=$(( byte | 0x80 )) | |
| fi | |
| printf '%b' "$(printf '\\x%02x' $byte)" | |
| [ $value -eq 0 ] && break | |
| done | |
| } | |
| ushort_encode() { | |
| printf "$(printf '\\x%02x\\x%02x' $(( ($1 >> 8) & 0xFF )) $(( $1 & 0xFF )))" | |
| } | |
| # base handshake | |
| { | |
| # packet id: 0x00 | |
| varint_encode 0 | |
| # encode our client version | |
| varint_encode "$VERSION" | |
| # encode server addr, port | |
| varint_encode "${#ADDR}" | |
| printf "%s" "$ADDR" | |
| ushort_encode "$PORT" | |
| # next state: status (0x01) | |
| varint_encode 1 | |
| } > .body.bin | |
| # main handshake payload | |
| { | |
| # add the length of the handshake | |
| varint_encode $(wc -c < .body.bin) | |
| cat .body.bin | |
| # status request packet | |
| varint_encode 1 | |
| varint_encode 0 | |
| } > handshake.bin | |
| rm .body.bin | |
| # pipe stderr to /dev/null | |
| # because when netcat timed out, it will warn us | |
| # in the stderr output. | |
| nc -q 30 -w 30 $ADDR $PORT 2>/dev/null < handshake.bin | |
| rm handshake.bin | |
| echo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment