如何在Go中获取本地IP地址?
问题描述:
我想获取计算机的IP地址.我使用了下面的代码,但它返回了127.0.0.1
.
I want to get the computer's IP address. I used the code below, but it returns 127.0.0.1
.
我想获取IP地址,例如10.32.10.111
,而不是回送地址.
I want to get the IP address, such as 10.32.10.111
, instead of the loopback address.
name, err := os.Hostname()
if err != nil {
fmt.Printf("Oops: %v\n", err)
return
}
addrs, err := net.LookupHost(name)
if err != nil {
fmt.Printf("Oops: %v\n", err)
return
}
for _, a := range addrs {
fmt.Println(a)
}
答
您需要遍历所有网络接口
You need to loop through all network interfaces
ifaces, err := net.Interfaces()
// handle err
for _, i := range ifaces {
addrs, err := i.Addrs()
// handle err
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
// process IP address
}
}
播放(取自util/helper.go)
Play (taken from util/helper.go)