Created
August 25, 2017 19:39
-
-
Save tsilvers/085c5f39430ced605d970094edf167ba to your computer and use it in GitHub Desktop.
Golang code to get MAC address for purposes of generating a unique id. Returns a uint64. Skips virtual MAC addresses (Locally Administered Addresses).
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 ( | |
"bytes" | |
"fmt" | |
"net" | |
) | |
func main() { | |
fmt.Printf("MAC: %16.16X\n", macUint64()) | |
} | |
func macUint64() uint64 { | |
interfaces, err := net.Interfaces() | |
if err != nil { | |
return uint64(0) | |
} | |
for _, i := range interfaces { | |
if i.Flags&net.FlagUp != 0 && bytes.Compare(i.HardwareAddr, nil) != 0 { | |
// Skip locally administered addresses | |
if i.HardwareAddr[0]&2 == 2 { | |
continue | |
} | |
var mac uint64 | |
for j, b := range i.HardwareAddr { | |
if j >= 8 { | |
break | |
} | |
mac <<= 8 | |
mac += uint64(b) | |
} | |
return mac | |
} | |
} | |
return uint64(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment