-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
whoami.go
59 lines (48 loc) · 1.2 KB
/
whoami.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
package killswitch
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/miekg/dns"
)
// WhoamiDNS return public ip by quering DNS server
func WhoamiDNS() (string, error) {
var record *dns.TXT
target := "o-o.myaddr.l.google.com"
server := "ns1.google.com"
c := dns.Client{}
m := dns.Msg{}
m.SetQuestion(target+".", dns.TypeTXT)
r, _, err := c.Exchange(&m, server+":53")
if err != nil {
return "", err
}
if len(r.Answer) == 0 {
return "", fmt.Errorf("could not found public IP")
}
for _, ans := range r.Answer {
record = ans.(*dns.TXT)
}
return strings.TrimSpace(record.Txt[0]), nil
}
// WhoamiWWW return IP by quering http server
func WhoamiWWW() (string, error) {
client := &http.Client{}
// Create request
req, _ := http.NewRequest("GET", "http://myip.country/ip", nil)
req.Header.Set("User-Agent", "killswitch")
// Fetch Request
resp, err := client.Do(req)
if err != nil {
req, _ = http.NewRequest("GET", "http://checkip.amazonaws.com/", nil)
req.Header.Set("User-Agent", "killswitch")
resp, err = client.Do(req)
if err != nil {
return "", err
}
}
// Read Response Body
respBody, _ := ioutil.ReadAll(resp.Body)
return strings.TrimSpace(string(respBody)), nil
}