再一次项目中,需要获取本地的ip地址,code:
package main
import (
"fmt"
"net"
)
func LocalIp() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
}
var ip string = "localhost"
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
}
}
}
return ip
}
func main() {
fmt.Println(LocalIp())
}
有疑问加站长微信联系(非本文作者)