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) }
Android. Select Settings from the application menu. Go to About Device > Status. Scroll down and look for the IP Address.
Usually, you can access the localhost of any computer through the loopback address 127.0. 0.1. By default, this IP address references a server running on the current device. In other words, when your computer requests the IP address 127.0.
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 }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With