gipv4_mac.go 930 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Copyright 2017 gf Author(https://github.com/gogf/gf). 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. )
  11. // GetMac retrieves and returns the first mac address of current host.
  12. func GetMac() (mac string, err error) {
  13. macs, err := GetMacArray()
  14. if err != nil {
  15. return "", err
  16. }
  17. if len(macs) > 0 {
  18. return macs[0], nil
  19. }
  20. return "", nil
  21. }
  22. // GetMacArray retrieves and returns all the mac address of current host.
  23. func GetMacArray() (macs []string, err error) {
  24. netInterfaces, err := net.Interfaces()
  25. if err != nil {
  26. return nil, err
  27. }
  28. for _, netInterface := range netInterfaces {
  29. macAddr := netInterface.HardwareAddr.String()
  30. if len(macAddr) == 0 {
  31. continue
  32. }
  33. macs = append(macs, macAddr)
  34. }
  35. return macs, nil
  36. }