forked from honwen/aliyun-ddns-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
86 lines (75 loc) · 1.63 KB
/
utils.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
package main
import (
"errors"
"net"
"reflect"
"github.com/honwen/golibs/cip"
)
var ipBlacklist = []string{
"127.0.0.0/8", "0.0.0.0/24",
}
var funcs = map[string]interface{}{
"myip": cip.MyIPv4,
"reslove": cip.ResloveIPv4,
}
func contains(slice []string, item string) bool {
set := make(map[string]struct{}, len(slice))
for _, s := range slice {
set[s] = struct{}{}
}
_, ok := set[item]
return ok
}
func Call(m map[string]interface{}, name string, params ...interface{}) (result []reflect.Value, err error) {
f := reflect.ValueOf(m[name])
if len(params) != f.Type().NumIn() {
err = errors.New("The number of params is not adapted.")
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
result = f.Call(in)
return
}
func containsCIDR(a, b *net.IPNet) bool {
ones1, _ := a.Mask.Size()
ones2, _ := b.Mask.Size()
return ones1 <= ones2 && a.Contains(b.IP)
}
func containsCIDRString(a, b string) (bool, error) {
_, net1, err := net.ParseCIDR(a)
if err != nil {
return false, err
}
_, net2, err := net.ParseCIDR(b)
if err != nil {
return false, err
}
result := containsCIDR(net1, net2)
return result, err
}
func myip() (ip string) {
if result, err := Call(funcs, "myip"); err == nil {
for _, r := range result {
ip = r.String()
for _, it := range ipBlacklist {
ok, _ := containsCIDRString(it, ip+`/32`)
if ok {
ip = ""
break
}
}
}
}
return
}
func reslove(domain string) (ip string) {
if result, err := Call(funcs, "reslove", domain); err == nil {
for _, r := range result {
return r.String()
}
}
return
}