v2ray-core/common/net/ipnet.go

84 lines
1.4 KiB
Go
Raw Normal View History

2015-12-08 16:31:31 +00:00
package net
import (
2017-08-29 09:31:16 +00:00
"math/bits"
2015-12-08 16:31:31 +00:00
"net"
)
2017-08-29 11:51:09 +00:00
type IPNetTable struct {
2015-12-08 16:31:31 +00:00
cache map[uint32]byte
}
2017-08-29 11:51:09 +00:00
func NewIPNetTable() *IPNetTable {
return &IPNetTable{
2016-10-18 14:42:22 +00:00
cache: make(map[uint32]byte, 1024),
2015-12-08 16:31:31 +00:00
}
}
2017-08-29 11:51:09 +00:00
func ipToUint32(ip IP) uint32 {
2015-12-08 16:31:31 +00:00
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) {
2017-08-29 09:31:16 +00:00
value += byte(bits.OnesCount8(b))
2015-12-08 16:31:31 +00:00
}
return value
}
2017-08-29 11:51:09 +00:00
func (n *IPNetTable) Add(ipNet *net.IPNet) {
2015-12-08 16:31:31 +00:00
ipv4 := ipNet.IP.To4()
if ipv4 == nil {
// For now, we don't support IPv6
return
}
mask := ipMaskToByte(ipNet.Mask)
2017-08-22 13:15:09 +00:00
n.AddIP(ipv4, mask)
2016-10-18 14:42:22 +00:00
}
2017-08-29 11:51:09 +00:00
func (n *IPNetTable) AddIP(ip []byte, mask byte) {
2016-10-18 14:42:22 +00:00
k := ipToUint32(ip)
k = (k >> (32 - mask)) << (32 - mask) // normalize ip
2017-08-22 13:15:09 +00:00
existing, found := n.cache[k]
2015-12-08 16:31:31 +00:00
if !found || existing > mask {
2017-08-22 13:15:09 +00:00
n.cache[k] = mask
2015-12-08 16:31:31 +00:00
}
}
2017-08-29 11:51:09 +00:00
func (n *IPNetTable) Contains(ip net.IP) bool {
2015-12-08 16:31:31 +00:00
ipv4 := ip.To4()
if ipv4 == nil {
return false
}
originalValue := ipToUint32(ipv4)
2017-08-22 13:15:09 +00:00
if entry, found := n.cache[originalValue]; found {
2016-10-19 13:38:31 +00:00
if entry == 32 {
2015-12-08 16:31:31 +00:00
return true
}
}
mask := uint32(0)
for maskbit := byte(1); maskbit <= 32; maskbit++ {
mask += 1 << uint32(32-maskbit)
maskedValue := originalValue & mask
2017-08-22 13:15:09 +00:00
if entry, found := n.cache[maskedValue]; found {
2015-12-08 16:31:31 +00:00
if entry == maskbit {
return true
}
}
}
return false
}
2017-08-29 11:51:09 +00:00
func (n *IPNetTable) IsEmpty() bool {
2017-08-22 13:15:09 +00:00
return len(n.cache) == 0
2015-12-08 16:31:31 +00:00
}