Last active
June 5, 2021 22:50
-
-
Save ben-z/3b18d1608868e6abf2212a435a216803 to your computer and use it in GitHub Desktop.
MAC Address Generator (Valid unicast locally administered address)
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
# MAC Address Generator | |
# Generates valid unicast locally administered addresses by | |
# setting bit 2 of the first byte and clearing bit 1 of the first byte. | |
# Documentation: http://www.noah.org/wiki/MAC_address | |
# Script URL: https://gist.github.com/ben-z/3b18d1608868e6abf2212a435a216803 | |
# https://stackoverflow.com/a/3265767/4527337 | |
function prettyprintmac { | |
echo $1 | sed -e 's/../&:/g' -e 's/:$//' | |
} | |
function cleaninputmac { | |
# takes in any 48-bit (6-byte) hex sequence (12 hex characters) below: | |
macaddr=$1 | |
# process the mac address | |
macaddr=${macaddr//.} # remove . | |
macaddr=${macaddr//:} # remove : | |
macaddr=${macaddr//-} # remove - | |
macaddr=${macaddr#0x} # remove prefix 0x | |
echo $macaddr | |
} | |
function isvalidmac { | |
macaddr=$(cleaninputmac $1) | |
# https://stackoverflow.com/a/7662661/4527337 | |
case $macaddr in | |
( *[!0-9A-Fa-f]* | "" ) return 1 ;; | |
( * ) | |
case ${#macaddr} in | |
# make sure it is 12 characters | |
( 12 ) return 0 ;; | |
( * ) return 1 ;; | |
esac | |
esac | |
} | |
function createunicastlocalmac { | |
macaddr=0x$macaddr | |
# output the mac address | |
printf "%x\n" "$(( (macaddr | 0x020000000000) & 0xfeffffffffff ))" | |
} | |
# parse input arguments | |
# https://stackoverflow.com/a/14203146/4527337 | |
for i in "$@" | |
do | |
case $i in | |
--stdin) | |
USE_STDIN=true | |
shift # past argument with no value | |
;; | |
*) | |
# unknown option | |
;; | |
esac | |
done | |
if [ -z "$USE_STDIN" ]; then | |
if ! isvalidmac $1; then | |
>&2 echo "\"$1\" is not a valid mac address!" | |
>&2 echo "Usage: $0 <mac_addr>" | |
>&2 echo "Usage2: $0 --stdin" | |
exit 1 | |
fi | |
macaddr=$(cleaninputmac $1) | |
echo "Input MAC: $(prettyprintmac $macaddr)" | |
outputmac=$(createunicastlocalmac $macaddr) | |
echo "Output MAC: $(prettyprintmac $outputmac)" | |
else | |
while IFS= read -r line; do | |
if ! isvalidmac $line; then | |
>&2 echo "\"$line\" is not a valid mac address!" | |
exit 1 | |
fi | |
inputmac=$(cleaninputmac "$line") | |
outputmac=$(createunicastlocalmac "$inputmac") | |
prettyprintmac $outputmac | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment