更好地支持IPv6

This commit is contained in:
刘祥超
2024-04-06 09:12:17 +08:00
parent 7c5c600e31
commit e54cfa7765
22 changed files with 1237 additions and 137 deletions

View File

@@ -1,41 +1,10 @@
package configutils
import (
"encoding/binary"
"math/big"
"net"
"strings"
)
// IPString2Long 将IP转换为整型
// 注意IPv6没有顺序
func IPString2Long(ip string) uint64 {
if len(ip) == 0 {
return 0
}
var netIP = net.ParseIP(ip)
if len(netIP) == 0 {
return 0
}
return IP2Long(netIP)
}
// IP2Long 将IP对象转换为整型
func IP2Long(netIP net.IP) uint64 {
if len(netIP) == 0 {
return 0
}
var b4 = netIP.To4()
if b4 != nil {
return uint64(binary.BigEndian.Uint32(b4.To4()))
}
var i = big.NewInt(0)
i.SetBytes(netIP.To16())
return i.Uint64()
}
// IsIPv4 检查是否为IPv4
func IsIPv4(netIP net.IP) bool {
if len(netIP) == 0 {

View File

@@ -3,7 +3,6 @@
package configutils_test
import (
"fmt"
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"github.com/iwind/TeaGo/assert"
"net"
@@ -16,12 +15,6 @@ func TestParseCIDR(t *testing.T) {
t.Log(configutils.ParseCIDR("192.168.1.1/16"))
}
func TestIPString2Long(t *testing.T) {
for _, ip := range []string{"127.0.0.1", "192.168.1.100", "::1", "fd00:6868:6868:0:10ac:d056:3bf6:7452", "fd00:6868:6868:0:10ac:d056:3bf6:7453", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", "wrong ip"} {
t.Log(fmt.Sprintf("%42s", ip), "=>", configutils.IPString2Long(ip))
}
}
func TestIsIPv4(t *testing.T) {
t.Log(configutils.IsIPv4(net.ParseIP("192.168.1.100")))
t.Log(configutils.IsIPv4(net.ParseIP("::1")))
@@ -40,7 +33,6 @@ func TestIPVersion(t *testing.T) {
a.IsTrue(configutils.IPVersion(net.ParseIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334")) == 6)
}
func TestQuoteIP(t *testing.T) {
t.Log(configutils.QuoteIP(configutils.QuoteIP("2001:da8:22::10")))
}
}