45 lines
671 B
Go
45 lines
671 B
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func GetPublicIP() (string, error) {
|
|
client := &http.Client{
|
|
Timeout: 10 * time.Second,
|
|
}
|
|
|
|
services := []string{
|
|
"https://api.ipify.org",
|
|
"https://icanhazip.com",
|
|
"https://ifconfig.me/ip",
|
|
}
|
|
|
|
for _, service := range services {
|
|
resp, err := client.Get(service)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
continue
|
|
}
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
ip := string(body)
|
|
if ip != "" {
|
|
return ip, nil
|
|
}
|
|
}
|
|
|
|
return "", fmt.Errorf("failed to determine public IP address from any service")
|
|
}
|