mirror of
https://github.com/YspCoder/clawgo.git
synced 2026-05-21 22:37:31 +08:00
nodes api: improve local IP detection with outbound dial fallback
This commit is contained in:
@@ -847,30 +847,39 @@ func detectWebUIVersion(webUIDir string) string {
|
|||||||
|
|
||||||
func detectLocalIP() string {
|
func detectLocalIP() string {
|
||||||
ifaces, err := net.Interfaces()
|
ifaces, err := net.Interfaces()
|
||||||
if err != nil {
|
if err == nil {
|
||||||
return ""
|
for _, iface := range ifaces {
|
||||||
}
|
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
|
||||||
for _, iface := range ifaces {
|
continue
|
||||||
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
|
}
|
||||||
continue
|
addrs, _ := iface.Addrs()
|
||||||
|
for _, a := range addrs {
|
||||||
|
var ip net.IP
|
||||||
|
switch v := a.(type) {
|
||||||
|
case *net.IPNet:
|
||||||
|
ip = v.IP
|
||||||
|
case *net.IPAddr:
|
||||||
|
ip = v.IP
|
||||||
|
}
|
||||||
|
if ip == nil || ip.IsLoopback() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ip = ip.To4()
|
||||||
|
if ip == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return ip.String()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
addrs, _ := iface.Addrs()
|
}
|
||||||
for _, a := range addrs {
|
// Fallback: detect outbound source IP.
|
||||||
var ip net.IP
|
conn, err := net.Dial("udp", "8.8.8.8:80")
|
||||||
switch v := a.(type) {
|
if err == nil {
|
||||||
case *net.IPNet:
|
defer conn.Close()
|
||||||
ip = v.IP
|
if ua, ok := conn.LocalAddr().(*net.UDPAddr); ok && ua.IP != nil {
|
||||||
case *net.IPAddr:
|
if ip := ua.IP.To4(); ip != nil {
|
||||||
ip = v.IP
|
return ip.String()
|
||||||
}
|
}
|
||||||
if ip == nil || ip.IsLoopback() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ip = ip.To4()
|
|
||||||
if ip == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return ip.String()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
|
|||||||
Reference in New Issue
Block a user