Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the local IP address in Go?

Tags:

go

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) }   
like image 345
Jerry YY Rain Avatar asked May 09 '14 07:05

Jerry YY Rain


People also ask

How do I find the local IP address of a device?

Android. Select Settings from the application menu. Go to About Device > Status. Scroll down and look for the IP Address.

How do I find my localhost?

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.


2 Answers

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 } 
like image 131
Mr.Wang from Next Door Avatar answered Oct 05 '22 19:10

Mr.Wang from Next Door


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)

like image 34
Sebastian Avatar answered Oct 05 '22 21:10

Sebastian