1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-03 01:38:24 -04:00
v2fly/common/net/ipnet.go

94 lines
1.5 KiB
Go
Raw Normal View History

2015-12-08 11:31:31 -05:00
package net
import (
"net"
)
var (
onesCount = make(map[byte]byte)
)
type IPNet struct {
cache map[uint32]byte
}
func NewIPNet() *IPNet {
return &IPNet{
2016-10-18 10:42:22 -04:00
cache: make(map[uint32]byte, 1024),
2015-12-08 11:31:31 -05:00
}
}
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
}
mask := ipMaskToByte(ipNet.Mask)
2016-10-18 10:42:22 -04:00
this.AddIP(ipv4, mask)
}
func (this *IPNet) AddIP(ip []byte, mask byte) {
k := ipToUint32(ip)
existing, found := this.cache[k]
2015-12-08 11:31:31 -05:00
if !found || existing > mask {
2016-10-18 10:42:22 -04:00
this.cache[k] = mask
2015-12-08 11:31:31 -05:00
}
}
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 {
2016-10-19 09:38:31 -04:00
if entry == 32 {
2015-12-08 11:31:31 -05:00
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
}
2016-10-18 10:42:22 -04:00
func (this *IPNet) IsEmpty() bool {
return len(this.cache) == 0
2015-12-08 11:31:31 -05:00
}
func init() {
value := byte(0)
for mask := byte(1); mask <= 8; mask++ {
value += 1 << byte(8-mask)
onesCount[value] = mask
}
}