1、获取mac地址和ip地址,需要使用golang的net模块,下面通过net模块
获取本机MAC地址
package getNetInfo
import (
"fmt"
"net"
)
func GetMac() (macAddrs []string) {
netInterfaces, err := net.Interfaces()
if err != nil {
fmt.Printf("fail to get net interfaces: %v\n", err)
return macAddrs
}
for _, netInterface := range netInterfaces {
macAddr := netInterface.HardwareAddr.String()
if len(macAddr) == 0 {
continue
}
macAddrs = append(macAddrs, macAddr)
}
return macAddrs
}
2、直接获取本机的MAC地址
func GetLocalMac()(mac string){
// 获取本机的MAC地址
interfaces, err := net.Interfaces()
if err != nil {
panic("Poor soul, here is what you got: " + err.Error())
}
for _, inter := range interfaces {
fmt.Println(inter.Name)
mac := inter.HardwareAddr //获取本机MAC地址
fmt.Println("MAC = ", mac)
}
return mac
}
3、获取IP地址
func GetIps() (ips []string) {
interfaceAddr, err := net.InterfaceAddrs()
if err != nil {
fmt.Printf("fail to get net interfaces ipAddress: %v\n", err)
return ips
}
for _, address := range interfaceAddr {
ipNet, isVailIpNet := address.(*net.IPNet)
// 检查ip地址判断是否回环地址
if isVailIpNet && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ips = append(ips, ipNet.IP.String())
}
}
}
return ips
}
注:go 语言在获取机器的 mac 地址和 ip 时,windows 和 linux 输出格式不一样,比如 windows 获取的 mac 地址是 8 个字节,而 linux 获取的 mac 是 6 个字节