You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/net/ipnet.go

94 lines
1.5 KiB

9 years ago
package net
import (
"net"
)
var (
onesCount = make(map[byte]byte)
)
type IPNet struct {
cache map[uint32]byte
}
func NewIPNet() *IPNet {
return &IPNet{
cache: make(map[uint32]byte, 1024),
9 years ago
}
}
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
}
8 years ago
func (v *IPNet) Add(ipNet *net.IPNet) {
9 years ago
ipv4 := ipNet.IP.To4()
if ipv4 == nil {
// For now, we don't support IPv6
return
}
mask := ipMaskToByte(ipNet.Mask)
8 years ago
v.AddIP(ipv4, mask)
}
8 years ago
func (v *IPNet) AddIP(ip []byte, mask byte) {
k := ipToUint32(ip)
8 years ago
existing, found := v.cache[k]
9 years ago
if !found || existing > mask {
8 years ago
v.cache[k] = mask
9 years ago
}
}
8 years ago
func (v *IPNet) Contains(ip net.IP) bool {
9 years ago
ipv4 := ip.To4()
if ipv4 == nil {
return false
}
originalValue := ipToUint32(ipv4)
8 years ago
if entry, found := v.cache[originalValue]; found {
if entry == 32 {
9 years ago
return true
}
}
mask := uint32(0)
for maskbit := byte(1); maskbit <= 32; maskbit++ {
mask += 1 << uint32(32-maskbit)
maskedValue := originalValue & mask
8 years ago
if entry, found := v.cache[maskedValue]; found {
9 years ago
if entry == maskbit {
return true
}
}
}
return false
}
8 years ago
func (v *IPNet) IsEmpty() bool {
return len(v.cache) == 0
9 years ago
}
func init() {
value := byte(0)
for mask := byte(1); mask <= 8; mask++ {
value += 1 << byte(8-mask)
onesCount[value] = mask
}
}