更好地支持IPv6/优化IP名单内存用量

This commit is contained in:
刘祥超
2024-04-06 10:07:39 +08:00
parent ece596d7b9
commit c9eb577c06
13 changed files with 254 additions and 241 deletions

View File

@@ -1,30 +1,10 @@
package utils
import (
"encoding/binary"
"github.com/cespare/xxhash"
"math"
"net"
"strings"
)
// IP2LongHash 非标地将IP转换为整型
// 注意IPv6没有顺序
func IP2LongHash(ip string) uint64 {
if len(ip) == 0 {
return 0
}
s := net.ParseIP(ip)
if len(s) == 0 {
return 0
}
if strings.Contains(ip, ":") {
return math.MaxUint32 + xxhash.Sum64(s)
}
return uint64(binary.BigEndian.Uint32(s.To4()))
}
// IsLocalIP 判断是否为本地IP
func IsLocalIP(ipString string) bool {
var ip = net.ParseIP(ipString)

View File

@@ -6,15 +6,6 @@ import (
"testing"
)
func TestIP2Long(t *testing.T) {
t.Log(utils.IP2LongHash("0.0.0.0"))
t.Log(utils.IP2LongHash("1.0.0.0"))
t.Log(utils.IP2LongHash("0.0.0.0.0"))
t.Log(utils.IP2LongHash("2001:db8:0:1::101"))
t.Log(utils.IP2LongHash("2001:db8:0:1::102"))
t.Log(utils.IP2LongHash("::1"))
}
func TestIsLocalIP(t *testing.T) {
var a = assert.NewAssertion(t)
a.IsFalse(utils.IsLocalIP("a"))

View File

@@ -1,7 +1,8 @@
package utils
import (
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"encoding/binary"
"net"
"strings"
)
@@ -15,5 +16,9 @@ func VersionToLong(version string) uint32 {
} else if countDots == 0 {
version += ".0.0.0"
}
return uint32(configutils.IPString2Long(version))
var ip = net.ParseIP(version)
if ip == nil || ip.To4() == nil {
return 0
}
return binary.BigEndian.Uint32(ip.To4())
}