go获取机器的mac地址和ip
2021-01-22 本文已影响0人
大地缸
title: "Go获取机器的mac地址和ip"
date: 2021-01-22T21:23:22+08:00
draft: true
tags: ['go']
author: "dadigang"
author_cn: "大地缸"
personal: "http://www.real007.cn"
关于作者
package main
import (
"fmt"
"net"
)
func getMacAddrs() (macAddrs []string) {
netInterfaces, err := net.Interfaces()
if err != nil {
fmt.Printf("fail to get net interfaces: %v", err)
return macAddrs
}
for _, netInterface := range netInterfaces {
macAddr := netInterface.HardwareAddr.String()
if len(macAddr) == 0 {
continue
}
macAddrs = append(macAddrs, macAddr)
}
return macAddrs
}
func getIPs() (ips []string) {
interfaceAddr, err := net.InterfaceAddrs()
if err != nil {
fmt.Printf("fail to get net interface addrs: %v", err)
return ips
}
for _, address := range interfaceAddr {
ipNet, isValidIpNet := address.(*net.IPNet)
if isValidIpNet && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ips = append(ips, ipNet.IP.String())
}
}
}
return ips
}
func main() {
fmt.Printf("mac addrs: %q\n", getMacAddrs())
fmt.Printf("ips: %q\n", getIPs())
}