Skip to content

Commit dd14d3b

Browse files
committed
Fix local ip address if multiple network interfaces
1 parent 059b625 commit dd14d3b

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

config/config.go

+19-2
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,29 @@ func getLocalIP() string {
3232
if err != nil {
3333
panic(err)
3434
}
35+
var ips []string
3536
for _, address := range addrs {
3637
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
3738
if ipnet.IP.To4() != nil {
38-
return ipnet.IP.String()
39+
ips = append(ips, ipnet.IP.String())
3940
}
4041
}
4142
}
42-
panic("get local ip failed")
43+
if len(ips) == 0 {
44+
panic("get local ip failed")
45+
} else if len(ips) == 1 {
46+
return ips[0]
47+
} else {
48+
// Select the one connected to the network
49+
// when there are multiple network interfaces
50+
51+
// Is there a better way?
52+
c, err := net.Dial("udp", "8.8.8.8:80")
53+
if err != nil {
54+
return ips[0]
55+
}
56+
defer c.Close()
57+
return c.LocalAddr().(*net.UDPAddr).IP.String()
58+
}
59+
4360
}

0 commit comments

Comments
 (0)