-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
108 lines (98 loc) · 2.18 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
107
108
package main
import (
"encoding/json"
"io/ioutil"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
ddns "github.com/jayschwa/go-dyndns"
log "github.com/sirupsen/logrus"
)
// Configuration holds the complete JSON configuration data
type Configuration struct {
Logfile string
DNSConfig []DNSConfig
}
// DNSConfig holds all data, that is used for connecting to the DNS Service
type DNSConfig struct {
URL string
Username string
Password string
Hostname string
}
func main() {
configuration := Configuration{}
file, err := os.Open("./config.json")
if err != nil {
log.Panic(err)
}
defer file.Close()
decoder := json.NewDecoder(file)
err = decoder.Decode(&configuration)
if err != nil {
log.Panic(err)
}
if configuration.Logfile != "" {
logfile, err := os.OpenFile(configuration.Logfile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Panic(err)
}
defer logfile.Close()
log.SetOutput(logfile)
}
for true {
ip, err := getGlobalIP()
if err != nil {
log.Panic(err)
}
for _, config := range configuration.DNSConfig {
s := ddns.Service{URL: config.URL, Username: config.Username, Password: config.Password}
currentIP, err := net.LookupIP(config.Hostname)
if err != nil {
log.Errorf("Lookup failed: %s", config.Hostname)
continue
}
if contains(currentIP, ip) {
log.Infof("nothing changed: %s", config.Hostname)
continue
}
_, err = s.Update(config.Hostname, ip)
if err == nil {
log.Infof("updated: %s", config.Hostname)
} else {
log.Panic(err)
}
}
log.Infof("Waiting %d Hours", 1)
time.Sleep(1 * time.Hour)
}
}
func getGlobalIP() (net.IP, error) {
response, err := http.Get("http://myexternalip.com/raw")
if err != nil {
return nil, err
}
defer response.Body.Close()
content, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
parts := strings.Split(string(content), ".")
var ips [4]byte
for i, a := range parts {
tmp, _ := strconv.Atoi(a)
ips[i] = byte(tmp)
}
return net.IPv4(ips[0], ips[1], ips[2], ips[3]), nil
}
func contains(currentIPS []net.IP, ip net.IP) bool {
for _, i := range currentIPS {
if i.Equal(ip) {
return true
}
}
return false
}