如何在 Go 中获取本地 IP 地址? [英] How do I get the local IP address in Go?
本文介绍了如何在 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
", err)
return
}
addrs, err := net.LookupHost(name)
if err != nil {
fmt.Printf("Oops: %v
", 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)
这篇关于如何在 Go 中获取本地 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文