Skip to content

Commit

Permalink
Fix local ip address if multiple network interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
chyok committed Nov 16, 2023
1 parent 059b625 commit dd14d3b
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,29 @@ func getLocalIP() string {
if err != nil {
panic(err)
}
var ips []string
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
ips = append(ips, ipnet.IP.String())
}
}
}
panic("get local ip failed")
if len(ips) == 0 {
panic("get local ip failed")
} else if len(ips) == 1 {
return ips[0]
} else {
// Select the one connected to the network
// when there are multiple network interfaces

// Is there a better way?
c, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return ips[0]
}
defer c.Close()
return c.LocalAddr().(*net.UDPAddr).IP.String()
}

}

0 comments on commit dd14d3b

Please sign in to comment.