Fetch IP address concurrently using multiple endpoints
This commit is contained in:
+53
-8
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user