Skip to content

Instantly share code, notes, and snippets.

@Miladbr
Created January 16, 2026 21:56
Show Gist options
  • Select an option

  • Save Miladbr/6658c4945286afe3c5be9a25fc3959e6 to your computer and use it in GitHub Desktop.

Select an option

Save Miladbr/6658c4945286afe3c5be9a25fc3959e6 to your computer and use it in GitHub Desktop.
dnstt balancer
#!/usr/bin/env bash
IPS=(
"217.144.106.205"
"94.184.10.82"
"5.190.1.83"
)
DOMAIN="t.<YOUR_DOMAIN>"
EXPECTED_NS="tns.<YOUR_DOMAIN>."
CHECK_INTERVAL=30
DIG_TIMEOUT=3
DNSTT_CMD="./dnstt"
DNSTT_ARGS="-udp %IP%:53 -pubkey-file server.pub $DOMAIN 127.0.0.1:9091"
PID_FILE="/tmp/dnstt.pid"
BEST_IP_FILE="/tmp/dnstt.best_ip"
get_best_ip() {
local best_ip=""
local best_time=999999
for ip in "${IPS[@]}"; do
start=$(date +%s%3N)
result=$(dig +time=$DIG_TIMEOUT +tries=1 +short NS "$DOMAIN" @"$ip" 2>/dev/null)
end=$(date +%s%3N)
elapsed=$((end - start))
if [[ "$result" == "$EXPECTED_NS" ]]; then
if (( elapsed < best_time )); then
best_time=$elapsed
best_ip=$ip
fi
fi
done
echo "$best_ip"
}
kill_dnstt() {
if [[ -f "$PID_FILE" ]]; then
pid=$(cat "$PID_FILE")
if kill -0 "$pid" 2>/dev/null; then
kill "$pid"
sleep 1
fi
rm -f "$PID_FILE"
else
pkill -f "$DNSTT_CMD" 2>/dev/null
fi
}
start_dnstt() {
local ip="$1"
cmd=${DNSTT_ARGS//%IP%/$ip}
nohup $DNSTT_CMD $cmd >/dev/null 2>&1 &
echo $! > "$PID_FILE"
}
while true; do
best_ip=$(get_best_ip)
if [[ -z "$best_ip" ]]; then
sleep "$CHECK_INTERVAL"
continue
fi
last_ip=""
[[ -f "$BEST_IP_FILE" ]] && last_ip=$(cat "$BEST_IP_FILE")
if [[ "$best_ip" != "$last_ip" ]]; then
kill_dnstt
start_dnstt "$best_ip"
echo "$best_ip" > "$BEST_IP_FILE"
fi
sleep "$CHECK_INTERVAL"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment