新博客地址(shankusu.me)
获取IP
package main
import (
"fmt"
"net"
"os"
)
func main() {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
fmt.Println(ipnet.IP.String())
}
}
}
}
获取MAC
package main
import (
"net"
"fmt"
)
func main() {
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, inter.HardwareAddr)
}
}