-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.go
More file actions
89 lines (70 loc) · 1.4 KB
/
helpers.go
File metadata and controls
89 lines (70 loc) · 1.4 KB
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
package networkvalidator
import (
"errors"
"math/big"
"net"
)
func getiprange(ipnet *net.IPNet, mask *net.IPMask) *rangeIp {
if ipnet == nil || mask == nil {
return nil
}
l, bits := mask.Size()
if l == bits {
lip := make([]byte, len(ipnet.IP))
copy(lip, ipnet.IP)
return &rangeIp{ipnet.IP, lip}
}
fip := inc(ipnet.IP)
fipint, bits, err := iptoint(fip)
if err != nil {
return nil
}
hlen := uint(bits) - uint(l)
lipint := big.NewInt(1)
lipint.Lsh(lipint, hlen)
lipint.Sub(lipint, big.NewInt(1))
lipint.Or(lipint, fipint)
e := dec(inttoip(lipint, bits))
return &rangeIp{fip, e}
}
func iptoint(ip net.IP) (*big.Int, int, error) {
v := &big.Int{}
v.SetBytes([]byte(ip))
if len(ip) == net.IPv4len {
return v, 32, nil
} else if len(ip) == net.IPv6len {
return v, 128, nil
} else {
return nil, -1, errors.New("unsupported length")
}
}
func inttoip(ip *big.Int, bits int) net.IP {
b := ip.Bytes()
ret := make([]byte, bits/8)
for i := 1; i <= len(b); i++ {
ret[len(ret)-i] = b[len(b)-i]
}
return net.IP(ret)
}
func inc(ip net.IP) net.IP {
incip := make([]byte, len(ip))
copy(incip, ip)
for i := len(incip) - 1; i >= 0; i-- {
incip[i]++
if incip[i] > 0 {
break
}
}
return incip
}
func dec(ip net.IP) net.IP {
decip := make([]byte, len(ip))
copy(decip, ip)
for i := len(decip) - 1; i >= 0; i -- {
decip[i] --
if decip[i] < 255 {
break
}
}
return decip
}