github.com/gogf/gf/v2@v2.7.4/net/gipv4/gipv4_mac.go (about) 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 8 package gipv4 9 10 import ( 11 "net" 12 13 "github.com/gogf/gf/v2/errors/gerror" 14 ) 15 16 // GetMac retrieves and returns the first mac address of current host. 17 func GetMac() (mac string, err error) { 18 macs, err := GetMacArray() 19 if err != nil { 20 return "", err 21 } 22 if len(macs) > 0 { 23 return macs[0], nil 24 } 25 return "", nil 26 } 27 28 // GetMacArray retrieves and returns all the mac address of current host. 29 func GetMacArray() (macs []string, err error) { 30 netInterfaces, err := net.Interfaces() 31 if err != nil { 32 err = gerror.Wrap(err, `net.Interfaces failed`) 33 return nil, err 34 } 35 for _, netInterface := range netInterfaces { 36 macAddr := netInterface.HardwareAddr.String() 37 if len(macAddr) == 0 { 38 continue 39 } 40 macs = append(macs, macAddr) 41 } 42 return macs, nil 43 }