Last active
August 15, 2025 19:48
-
-
Save bp2008/9d5736a81998fdedb13adb72cec0d39f 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
#!/bin/bash | |
# This bash script helps find the maximum MTU for the path to the given hostname. Supports IPv4 and IPv6. | |
# If your connection is experiencing packet loss, the result may be lower than the true MTU. Run the script multiple times to be certain. | |
# This script written mainly by Copilot on 2025-08-15. | |
# Usage: ./find_max_mtu.sh [-m min_mtu] [-M max_mtu] <destination> | |
# Example: ./find_max_mtu.sh google.com | |
# Example: ./find_max_mtu.sh -m 1280 -M 1460 google.com | |
# Default MTU range | |
MIN=1200 | |
MAX=1500 | |
# Parse options | |
while getopts ":m:M:" opt; do | |
case $opt in | |
m) | |
MIN="$OPTARG" | |
;; | |
M) | |
MAX="$OPTARG" | |
;; | |
\?) | |
echo "Invalid option: -$OPTARG" >&2 | |
exit 1 | |
;; | |
:) | |
echo "Option -$OPTARG requires an argument." >&2 | |
exit 1 | |
;; | |
esac | |
done | |
shift $((OPTIND -1)) | |
DEST="$1" | |
if [[ -z "$DEST" ]]; then | |
echo "Usage: $0 [-m min_mtu] [-M max_mtu] <destination>" | |
exit 1 | |
fi | |
# Resolve IP type | |
IP=$(getent ahosts "$DEST" | awk '/STREAM/ { print $1; exit }') | |
if [[ -z "$IP" ]]; then | |
echo "❌ Failed to resolve $DEST" | |
exit 2 | |
fi | |
if [[ "$IP" == *:* ]]; then | |
TYPE="IPv6" | |
HEADER_OFFSET=48 # IPv6 header (40) + ICMPv6 (8) | |
PING_COMMAND="ping6" | |
else | |
TYPE="IPv4" | |
HEADER_OFFSET=28 # IPv4 header (20) + ICMP (8) | |
PING_COMMAND="ping" | |
fi | |
echo "🌐 Resolved $DEST to $IP ($TYPE)" | |
echo "Using $PING_COMMAND with header offset $HEADER_OFFSET" | |
echo "Testing MTU range: $MIN to $MAX. Override with -m MIN -M MAX." | |
echo "⚠️ Note: Packet loss can affect accuracy. Multiple runs may be required." | |
RESULT="Unknown" | |
while (( MIN <= MAX )); do | |
MID=$(( (MIN + MAX) / 2 )) | |
PAYLOAD=$(( MID - HEADER_OFFSET )) | |
$PING_COMMAND -c 1 -M do -s "$PAYLOAD" "$IP" > /dev/null 2>&1 | |
if [[ $? -eq 0 ]]; then | |
echo "MTU $MID OK" | |
RESULT=$MID | |
MIN=$(( MID + 1 )) | |
else | |
echo "MTU $MID FAIL" | |
MAX=$(( MID - 1 )) | |
fi | |
done | |
echo "✅ Maximum usable MTU to $DEST ($TYPE) is: $RESULT bytes." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment