I want to get the computer's IP address. I used the code below, but it returns 127.0.0.1
.
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
}
}
Play (taken from util/helper.go)