一、获取本机的Mac 和ip地址
1.获取本机的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)
}
fmt.Println("MAC = ", mac)
return mac
}
2.获取本机ip地址
代码如下(示例):
//获取本机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)
if isVailIpNet && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ips = append(ips, ipNet.IP.String())
}
}
}
fmt.Println("ips = ", ips)
return ips
}