-
Notifications
You must be signed in to change notification settings - Fork 0
/
public_ip.go
69 lines (60 loc) · 1.25 KB
/
public_ip.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
package p2p
import (
"io/ioutil"
"net"
"net/http"
"strings"
"time"
)
var ipCheckServices = []string{
"http://ifconfig.me/",
"http://icanhazip.com/",
"http://ifconfig.io/ip",
"http://ident.me/",
"http://whatismyip.akamai.com/",
"http://myip.dnsomatic.com/",
"http://diagnostic.opendns.com/myip",
"http://myexternalip.com/raw",
}
// IPResult is the ip check response
type IPResult struct {
Success bool
IP string
}
var timeout = time.Duration(5)
// GetIP return the ip of the current host
func GetIP() *IPResult {
resultCh := make(chan *IPResult, 1)
for _, s := range ipCheckServices {
go ipAddress(s, resultCh)
}
for {
select {
case result := <-resultCh:
return result
case <-time.After(time.Second * timeout):
return &IPResult{false, ""}
}
}
}
func ipAddress(service string, done chan<- *IPResult) {
client := http.Client{Timeout: time.Duration(timeout * time.Second)}
resp, err := client.Get(service)
if err != nil {
return
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
address := strings.TrimSpace(string(data))
if ip := net.ParseIP(address); ip != nil && ip.To4() != nil {
select {
case done <- &IPResult{true, address}:
return
default:
return
}
}
}