gf/net/gipv4/gipv4_mac.go

41 lines
915 B
Go

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
//
package gipv4
import (
"net"
)
// Mac retrieves and returns the first mac address of current host.
func Mac() (mac string, err error) {
macs, err := MacArray()
if err != nil {
return "", err
}
if len(macs) > 0 {
return macs[0], nil
}
return "", nil
}
// MacArray retrieves and returns all the mac address of current host.
func MacArray() (macs []string, err error) {
netInterfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, netInterface := range netInterfaces {
macAddr := netInterface.HardwareAddr.String()
if len(macAddr) == 0 {
continue
}
macs = append(macs, macAddr)
}
return macs, nil
}