-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
106 lines (91 loc) · 1.89 KB
/
main.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path"
"time"
"github.com/mitchellh/go-homedir"
)
const (
ipCheckURL = "https://ieserver.net/ipcheck.shtml"
timeout = time.Second * 10
ddnsUpdateURL = "https://ieserver.net/cgi-bin/dip.cgi"
)
var httpClient = http.Client{Timeout: time.Duration(timeout)}
func getGlobalIPValue() string {
resp, err := httpClient.Get(ipCheckURL)
if err != nil {
log.Fatalf("%v\n", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Fatalln(resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("%v\n", err)
}
return string(b)
}
type config struct {
Account string
Domain string
Passwd string
}
func readConfig(cfgPath string) config {
configPath := ""
if cfgPath == "" {
dir, err := homedir.Dir()
if err != nil {
log.Fatalf("%v\n", err)
}
configPath = path.Join(dir, ".ieserver.cfg")
} else {
configPath = cfgPath
}
if _, err := os.Stat(configPath); err != nil {
log.Fatalf("%v\n", err)
}
buf, err := ioutil.ReadFile(configPath)
if err != nil {
log.Fatalf("%v\n", err)
}
cfg := config{}
if err = json.Unmarshal(buf, &cfg); err != nil {
log.Fatalf("%v\n", err)
}
return cfg
}
func registerIP(ip string, cfg config) {
val := url.Values{
"username": {cfg.Account},
"domain": {cfg.Domain},
"password": {cfg.Passwd},
"updatehost": {"1"},
}
resp, err := httpClient.PostForm(ddnsUpdateURL, val)
if err != nil {
log.Fatalf("%v\n", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Fatalln(resp.Status)
}
log.Printf("done")
}
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
cfgPath := flag.String("c", "", "path to config file")
flag.Parse()
cfg := readConfig(*cfgPath)
ipString := getGlobalIPValue()
if ipString == "" {
log.Fatalf("can't fetch ip")
}
registerIP(ipString, cfg)
}