Last active
January 10, 2022 01:27
-
-
Save seansch/56fcf5a7423dbc11b344648fba35df51 to your computer and use it in GitHub Desktop.
Generate Unique IPv6 Local Network
This file contains 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 | |
# Generates a unique local IPv6 network | |
# Based on RFC4193 https://www.rfc-editor.org/rfc/rfc4193#section-3.2.2 | |
QUIET=0 | |
while getopts :hqs: flag | |
do | |
case "${flag}" in | |
q) # Only output network prefix | |
QUIET=1 | |
;; | |
s) # Specify 4 hexadecmil digits for subnet | |
SUBNET=${OPTARG} | |
;; | |
h | *) # Display help | |
echo "Generates a RFC4193 compliant unique IPv6 local network prefix" | |
echo "-q Only output network prefix" | |
echo "-s Specify 4 hexadecmil digits for subnet" | |
echo "-h Display help" | |
exit 0 | |
;; | |
esac | |
done | |
if [ ! -z $SUBNET ]; then | |
if [ ${#SUBNET} -ne 4 ] || ! [[ $SUBNET =~ ^[0-9A-Fa-f]{1,}$ ]]; then | |
echo "Subnet can only be 4 hexadecimal characters" | |
exit 0 | |
fi | |
fi | |
# Concatenate the current timestamp and machine ID | |
# Use sha1sum to geneate a hash | |
# Save the last 14 characters as the network hash | |
HASH=$(echo -n "$(date +%s%N)""$(cat /etc/machine-id)" | sha1sum | awk '{print substr($0,27,14)}') | |
# Use the last 10 characters from the network hash to generate a network | |
PREFIX=$(echo $HASH | awk '{print "fd" substr($0,4,2) ":" substr($0,7,4) ":" substr($0,11,4)}') | |
GID=$(echo $PREFIX | awk '{print substr($0,3)}') | |
if [ -z $SUBNET ]; then | |
# Not part of the RFC; use the first 4 characters from the hash for a random subnet | |
# Any subnet can be used if needed; ie. 0000, 0001, 8A7C | |
SUBNET=$(echo $HASH | awk '{print substr($0,0,4)}') | |
fi | |
if [ $QUIET -eq 1 ];then | |
echo "$PREFIX":"$SUBNET"::/64 | |
else | |
echo Gloabl ID: "$GID" | |
echo Unique Prefix: "$PREFIX"::/64 | |
echo Subnet: "$PREFIX":"$SUBNET"::/64 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment