From 7a4c010a4589762107e4ef9cbba7a09230c43e90 Mon Sep 17 00:00:00 2001 From: starry <115192496+sky22333@users.noreply.github.com> Date: Sat, 27 Dec 2025 06:08:26 +0800 Subject: [PATCH] Fetch IP address concurrently using multiple endpoints --- cmd/setting.go | 61 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 53 insertions(+), 8 deletions(-) diff --git a/cmd/setting.go b/cmd/setting.go index 22ea55e..a090cc2 100644 --- a/cmd/setting.go +++ b/cmd/setting.go @@ -5,6 +5,8 @@ import ( "io" "net/http" "strings" + "sync" + "time" "github.com/alireza0/s-ui/config" "github.com/alireza0/s-ui/database" @@ -110,6 +112,54 @@ func showSetting() { } } +func getPublicIP() string { + apis := []string{ + "https://api64.ipify.org", + "https://ip.sb", + "https://icanhazip.com", + "https://ipinfo.io/ip", + "https://checkip.amazonaws.com", + } + type result struct { + ip string + err error + } + ch := make(chan result, len(apis)) + var wg sync.WaitGroup + client := &http.Client{Timeout: 3 * time.Second} + + for _, api := range apis { + wg.Add(1) + go func(url string) { + defer wg.Done() + resp, err := client.Get(url) + if err != nil { + ch <- result{"", err} + return + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + ch <- result{"", err} + return + } + ch <- result{string(body), nil} + }(api) + } + + go func() { + wg.Wait() + close(ch) + }() + + for res := range ch { + if res.err == nil && res.ip != "" { + return strings.TrimSpace(res.ip) + } + } + return "" +} + func getPanelURI() { err := database.InitDB(config.GetDBPath()) if err != nil { @@ -146,7 +196,6 @@ func getPanelURI() { return } fmt.Println("Local address:") - // get ip address netInterfaces, _ := net.Interfaces() for i := 0; i < len(netInterfaces); i++ { if len(netInterfaces[i].Flags) > 2 && netInterfaces[i].Flags[0] == "up" && netInterfaces[i].Flags[1] != "loopback" { @@ -161,12 +210,8 @@ func getPanelURI() { } } } - resp, err := http.Get("https://api.ipify.org?format=text") - if err == nil { - defer resp.Body.Close() - ip, err := io.ReadAll(resp.Body) - if err == nil { - fmt.Printf("\nGlobal address:\n%s%s%s%s\n", Proto, ip, PortText, BasePath) - } + pubIP := getPublicIP() + if pubIP != "" { + fmt.Printf("\nGlobal address:\n%s%s%s\n", Proto, pubIP, PortText+BasePath) } }