1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 10:37:09 -05:00
v2fly/common/net/ipnet.go

84 lines
1.4 KiB
Go
Raw Normal View History

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