-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutil.go
77 lines (69 loc) · 1.38 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package discovery
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"sync"
)
func GetLocalIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
panic(err)
}
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
return ipNet.IP.String(), nil
}
}
}
return "", fmt.Errorf("no ip address found")
}
func GetPublicIP() (string, error) {
var wg sync.WaitGroup
urls := []string{
"https://checkip.amazonaws.com",
// "https://ident.me",
// "https://ifconfig.cc/ip",
// "https://ipinfo.io/ip",
// "https://ifconfig.co/ip",
// "https://ifconfig.io/ip",
// "https://ifconfig.me/ip",
}
ch := make(chan string, len(urls))
reqIp := func(apiURL string) (string, error) {
resp, err := http.Get(apiURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("status code: %d", resp.StatusCode)
}
ip, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return strings.Trim(string(ip), "\n"), nil
}
for _, url := range urls {
wg.Add(1)
go func(apiURL string) {
defer wg.Done()
ip, err := reqIp(apiURL)
if err == nil {
ch <- ip
}
}(url)
}
go func() {
wg.Wait()
close(ch)
}()
for ip := range ch {
return ip, nil
}
return "", fmt.Errorf("no ip address found")
}