forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipnet.go
97 lines (83 loc) · 1.68 KB
/
ipnet.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
package net
import (
"net"
)
var (
onesCount = make(map[byte]byte)
)
type IPNet struct {
cache map[uint32]byte
}
func NewIPNet() *IPNet {
return NewIPNetInitialValue(make(map[uint32]byte, 1024))
}
func NewIPNetInitialValue(data map[uint32]byte) *IPNet {
return &IPNet{
cache: data,
}
}
func ipToUint32(ip net.IP) uint32 {
value := uint32(0)
for _, b := range []byte(ip) {
value <<= 8
value += uint32(b)
}
return value
}
func ipMaskToByte(mask net.IPMask) byte {
value := byte(0)
for _, b := range []byte(mask) {
value += onesCount[b]
}
return value
}
func (this *IPNet) Add(ipNet *net.IPNet) {
ipv4 := ipNet.IP.To4()
if ipv4 == nil {
// For now, we don't support IPv6
return
}
value := ipToUint32(ipv4)
mask := ipMaskToByte(ipNet.Mask)
existing, found := this.cache[value]
if !found || existing > mask {
this.cache[value] = mask
}
}
func (this *IPNet) Contains(ip net.IP) bool {
ipv4 := ip.To4()
if ipv4 == nil {
return false
}
originalValue := ipToUint32(ipv4)
if entry, found := this.cache[originalValue]; found {
if entry == 0 {
return true
}
}
mask := uint32(0)
for maskbit := byte(1); maskbit <= 32; maskbit++ {
mask += 1 << uint32(32-maskbit)
maskedValue := originalValue & mask
if entry, found := this.cache[maskedValue]; found {
if entry == maskbit {
return true
}
}
}
return false
}
func (this *IPNet) Serialize() []uint32 {
content := make([]uint32, 0, 2*len(this.cache))
for key, value := range this.cache {
content = append(content, uint32(key), uint32(value))
}
return content
}
func init() {
value := byte(0)
for mask := byte(1); mask <= 8; mask++ {
value += 1 << byte(8-mask)
onesCount[value] = mask
}
}