-
Notifications
You must be signed in to change notification settings - Fork 0
/
getip.go
80 lines (67 loc) · 1.35 KB
/
getip.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
package main
import (
"errors"
"github.com/miekg/dns"
)
type dnsClient struct {
*dns.Client
resolvers []*dnsResolver
}
type dnsResolver struct {
questionDomain string
host string
}
func DefaultDnsClient() *dnsClient {
return &dnsClient{
Client: new(dns.Client),
resolvers: []*dnsResolver{
{
"myip.opendns.com",
"resolver1.opendns.com:53",
},
{
"o-o.myaddr.l.google.com",
"ns1.google.com:53",
},
},
}
}
// GetIP Get public ip address
func GetIP() (string, error) {
return DefaultDnsClient().getIP()
}
func (c *dnsClient) getIP() (ip string, err error) {
for _, r := range c.resolvers {
msg := newDnsMsg(r.questionDomain)
resp, _, err := c.Exchange(msg, r.host)
if err != nil {
continue
}
if resp.Rcode != dns.RcodeSuccess {
continue
}
ip, err := extractIP(resp)
if err != nil {
continue
}
return ip, nil
}
return "", errors.New("failed to query ip")
}
func newDnsMsg(questionDomain string) *dns.Msg {
msg := new(dns.Msg)
msg.RecursionDesired = false
msg.SetQuestion(dns.Fqdn(questionDomain), dns.TypeANY)
return msg
}
func extractIP(msg *dns.Msg) (ip string, err error) {
for _, rr := range msg.Answer {
if t, ok := rr.(*dns.TXT); ok {
return t.Txt[0], nil
}
if a, ok := rr.(*dns.A); ok {
return a.A.String(), nil
}
}
return "", errors.New("failed to extract ip")
}