2021-01-18 12:35:29 +08:00
|
|
|
package utils
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/binary"
|
2021-02-02 19:29:36 +08:00
|
|
|
"github.com/cespare/xxhash/v2"
|
|
|
|
|
"math"
|
2021-01-18 12:35:29 +08:00
|
|
|
"net"
|
2021-02-02 19:29:36 +08:00
|
|
|
"strings"
|
2021-01-18 12:35:29 +08:00
|
|
|
)
|
|
|
|
|
|
2021-06-07 10:02:07 +08:00
|
|
|
// IP2Long 将IP转换为整型
|
2021-02-02 19:29:36 +08:00
|
|
|
// 注意IPv6没有顺序
|
|
|
|
|
func IP2Long(ip string) uint64 {
|
|
|
|
|
if len(ip) == 0 {
|
|
|
|
|
return 0
|
|
|
|
|
}
|
2021-01-18 12:35:29 +08:00
|
|
|
s := net.ParseIP(ip)
|
2021-02-02 19:29:36 +08:00
|
|
|
if len(s) == 0 {
|
2021-01-18 12:35:29 +08:00
|
|
|
return 0
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-02 19:29:36 +08:00
|
|
|
if strings.Contains(ip, ":") {
|
|
|
|
|
return math.MaxUint32 + xxhash.Sum64(s)
|
2021-01-18 12:35:29 +08:00
|
|
|
}
|
2021-02-02 19:29:36 +08:00
|
|
|
return uint64(binary.BigEndian.Uint32(s.To4()))
|
2021-01-18 12:35:29 +08:00
|
|
|
}
|
2021-06-07 10:02:07 +08:00
|
|
|
|
|
|
|
|
// IsIPv6 判断是否为IPv6
|
|
|
|
|
func IsIPv6(ip string) bool {
|
|
|
|
|
return strings.Contains(ip, ":")
|
|
|
|
|
}
|