gipv4_mac.go 1013 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. //
  7. package gipv4
  8. import (
  9. "net"
  10. "github.com/gogf/gf/v2/errors/gerror"
  11. )
  12. // GetMac retrieves and returns the first mac address of current host.
  13. func GetMac() (mac string, err error) {
  14. macs, err := GetMacArray()
  15. if err != nil {
  16. return "", err
  17. }
  18. if len(macs) > 0 {
  19. return macs[0], nil
  20. }
  21. return "", nil
  22. }
  23. // GetMacArray retrieves and returns all the mac address of current host.
  24. func GetMacArray() (macs []string, err error) {
  25. netInterfaces, err := net.Interfaces()
  26. if err != nil {
  27. err = gerror.Wrap(err, `net.Interfaces failed`)
  28. return nil, err
  29. }
  30. for _, netInterface := range netInterfaces {
  31. macAddr := netInterface.HardwareAddr.String()
  32. if len(macAddr) == 0 {
  33. continue
  34. }
  35. macs = append(macs, macAddr)
  36. }
  37. return macs, nil
  38. }