script_collection/to_ip4.sh

37 lines
941 B
Bash
Executable File

#!/bin/bash
# Step 0: Make sure we have an argument
if [ -z "$1" ]; then
echo "Usage: $0 <input_string> (input string being last two blocks of ip6, e.g. fe36:d00f)"
exit 1
fi
input=$1
# Step 1: Split the input string at ":"
IFS=':' read -r part1 part2 <<< "$input"
# Step 2: Pad each of the two fields to 4 characters by adding leading zeros
part1=$(printf '%04x' 0x$part1)
part2=$(printf '%04x' 0x$part2)
# Step 3: Split each of the four-digit numbers into two digit numbers
# e.g., 4f33 becomes 4f and 33
part1a=${part1:0:2}
part1b=${part1:2:2}
part2a=${part2:0:2}
part2b=${part2:2:2}
# Step 4: Translate each hexadecimal two-digit number into decimal
decimal1a=$(printf '%d' 0x$part1a)
decimal1b=$(printf '%d' 0x$part1b)
decimal2a=$(printf '%d' 0x$part2a)
decimal2b=$(printf '%d' 0x$part2b)
# Step 5: Concat all numbers with a point '.'
result="$decimal1a.$decimal1b.$decimal2a.$decimal2b"
# Output the result
echo "$result"