util/net/converter/mac.go

44 lines
873 B
Go
Raw Normal View History

2017-09-11 07:42:19 +00:00
package converter
import (
"net"
"regexp"
"strconv"
"strings"
)
var (
macStripRegexp = regexp.MustCompile(`[^a-fA-F0-9]`)
)
func MacToUint(hwAddr net.HardwareAddr) (uint64, error) {
mac := hwAddr.String()
hex := macStripRegexp.ReplaceAllLiteralString(mac, "")
return strconv.ParseUint(hex, 16, 64)
}
func MacToInt(IPv4Addr net.HardwareAddr) int64 {
bits := strings.Split(IPv4Addr.String(), ":")
b0, _ := strconv.ParseInt(bits[0], 16, 64)
b1, _ := strconv.ParseInt(bits[1], 16, 64)
b2, _ := strconv.ParseInt(bits[2], 16, 64)
b3, _ := strconv.ParseInt(bits[3], 16, 64)
b4, _ := strconv.ParseInt(bits[4], 16, 64)
b5, _ := strconv.ParseInt(bits[5], 16, 64)
var sum int64
//52242420297
//52242420297
sum += int64(b0) << 40
sum += int64(b1) << 32
sum += int64(b2) << 24
sum += int64(b3) << 16
sum += int64(b4) << 8
sum += int64(b5)
return sum
}