Files
EdgeAPI/internal/utils/ip.go

32 lines
508 B
Go
Raw Normal View History

package utils
import (
"encoding/binary"
2021-02-02 19:29:36 +08:00
"github.com/cespare/xxhash/v2"
"math"
"net"
2021-02-02 19:29:36 +08:00
"strings"
)
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
}
s := net.ParseIP(ip)
2021-02-02 19:29:36 +08:00
if len(s) == 0 {
return 0
}
2021-02-02 19:29:36 +08:00
if strings.Contains(ip, ":") {
return math.MaxUint32 + xxhash.Sum64(s)
}
2021-02-02 19:29:36 +08:00
return uint64(binary.BigEndian.Uint32(s.To4()))
}
2021-06-07 10:02:07 +08:00
// IsIPv6 判断是否为IPv6
func IsIPv6(ip string) bool {
return strings.Contains(ip, ":")
}