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
To ensure that you get a non-loopback address, simply check that an IP is not a loopback when you are iterating.
// GetLocalIP returns the non loopback local IP of the host
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}