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
func resolveHostIp() (string) {
netInterfaceAddresses, err := net.InterfaceAddrs()
if err != nil { return "" }
for _, netInterfaceAddress := range netInterfaceAddresses {
networkIp, ok := netInterfaceAddress.(*net.IPNet)
if ok && !networkIp.IP.IsLoopback() && networkIp.IP.To4() != nil {
ip := networkIp.IP.String()
fmt.Println("Resolved Host IP: " + ip)
return ip
}
}
return ""
}
Here is a better solution to retrieve the preferred outbound ip address when there are multiple ip interfaces exist on the machine.
import (
"log"
"net"
"strings"
)
// Get preferred outbound ip of this machine
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}