/
public_ip.go
executable file
·91 lines (86 loc) · 2.22 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package gnet
import (
"github.com/davidforest123/goutil/basic/gerrors"
"github.com/davidforest123/goutil/container/gstring"
"github.com/davidforest123/goutil/net/ghtml"
"github.com/davidforest123/goutil/net/ghttp"
"github.com/davidforest123/goutil/net/gprobe/xonline"
"net"
"strings"
"time"
)
// get my wan IPs by 3rd party service
func GetPublicIPOL(proxy string) (net.IP, error) {
var ipstr string
var exist bool
var firstCheckWanOnline = true
// best choices: plain text of ip string
endpoints := []string{
"http://whatismyip.akamai.com",
"http://ident.me",
"http://myip.dnsomatic.com",
"http://icanhazip.com",
"http://ifconfig.co/ip"}
eps := gstring.Shuffle(endpoints)
for _, url := range eps {
resp, err := ghttp.Get(url, proxy, time.Second*3, true)
if err != nil {
if firstCheckWanOnline {
if !xonline.IsWanOnline(proxy) {
return nil, gerrors.New("Can't get WAN ip because of internet offline ")
}
firstCheckWanOnline = false
}
continue
}
ipstr, _ = ghttp.ReadBodyString(resp)
resp.Body.Close()
ipstr = strings.Trim(ipstr, "\r") // icanhazip.com 的返回结果会带换行符
ipstr = strings.Trim(ipstr, "\n")
t, err := ParseIP(ipstr)
if err != nil {
return nil, err
}
if t.IsPublic() && t.IsV4() {
return t.Raw(), nil
}
}
// backup choices
htmlString, err := ghttp.GetString("http://bot.whatismyipaddress.com", proxy, time.Second*5)
if err != nil {
return nil, err
}
doc, err := ghtml.NewDocFromHtmlSrc(&htmlString)
if err == nil {
ipstr = doc.Text()
t, err := ParseIP(ipstr)
if err != nil {
return nil, err
}
if t.IsPublic() && t.IsV4() {
return t.Raw(), nil
}
}
htmlString, err = ghttp.GetString("http://network-tools.com", proxy, time.Second*5)
if err != nil {
return nil, err
}
doc, err = ghtml.NewDocFromHtmlSrc(&htmlString)
if err == nil {
ipstr, exist = doc.Find("#field").First().Attr("value")
if exist {
t, err := ParseIP(ipstr)
if err != nil {
return nil, err
}
if t.IsPublic() && t.IsV4() {
return t.Raw(), nil
}
}
}
if !xonline.IsWanOnline(proxy) {
return nil, gerrors.New("Can't get WAN ip because of internet offline ")
} else {
return nil, gerrors.New("Can't get WAN ip, unknown error")
}
}