可以使用net包中的接口函数来获取指定网卡的mac地址和IP地址。
获取mac地址:
package main
import (
"fmt"
"net"
)
func main() {
ifaces, err := net.Interfaces()
if err != nil {
fmt.Println(err)
return
}
for _, iface := range ifaces {
if iface.Name == "eth0" {
fmt.Println("MAC address: ", iface.HardwareAddr)
}
}
}
其中,net.Interfaces()
函数返回当前系统上所有网络接口的信息列表。通过遍历这个列表,找到名称为“eth0”的网络接口,就可以获取它的MAC地址了。
获取IP地址:
package main
import (
"fmt"
"net"
)
func main() {
ifaces, err := net.Interfaces()
if err != nil {
fmt.Println(err)
return
}
for _, iface := range ifaces {
if iface.Name == "eth0" {
addrs, err := iface.Addrs()
if err != nil {
fmt.Println(err)
continue
}
for _, addr := range addrs {
ipnet, ok := addr.(*net.IPNet)
if ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
fmt.Println("IPv4 address: ", ipnet.IP.String())
} else {
fmt.Println("IPv6 address: ", ipnet.IP.String())
}
}
}
}
}
}
类似地,首先遍历网络接口信息列表,找到目标接口“eth0”,然后调用iface.Addrs()
方法获取该接口上的所有IP地址。遍历这些IP地址,判断是IPv4还是IPv6,并输出对应的地址即可。