Last active
October 12, 2018 14:58
-
-
Save IkiM0no/77edc82bdaf3081407fa93de7ac7e314 to your computer and use it in GitHub Desktop.
normalize mac address to standard format
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
package main | |
import ( | |
"log" | |
"regexp" | |
"strings" | |
) | |
var macRegex = regexp.MustCompile(`^([0-9A-Fa-f]{2}[:-]?){5}([0-9A-Fa-f]{2})$`) | |
func main() { | |
macs := []string{ | |
"EC-9B-F3-58-05-BA", | |
"a1:3c:b2:58:05:ba", | |
"a13cb25805ba", | |
"LULZ NOT A MAC"} | |
for _, m := range macs { | |
s, err := NomalizeMac(m) | |
if err != nil { | |
log.Printf("%s: %s\n", err, m) | |
} else { | |
log.Printf("mac ok. original: %s, normalized: %s\n", m, s) | |
} | |
} | |
} | |
func NomalizeMac(mac string) (string, error) { | |
r := strings.NewReplacer(":", "", "-", "") | |
if macRegex.MatchString(mac) { | |
return strings.ToLower(r.Replace(mac)), nil | |
} | |
return "", ErrInvalidMacAddress | |
} | |
type Error string | |
func (e Error) Error() string { return string(e) } | |
const ErrInvalidMacAddress = Error("invalid mac address") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment