2017-09-11 09:09:01 +00:00
|
|
|
package converter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
func IPToUint64(ip string) uint64 {
|
|
|
|
isV4 := true
|
|
|
|
for i := 0; i < len(ip); i++ {
|
|
|
|
switch ip[i] {
|
|
|
|
case ':':
|
|
|
|
isV4 = false
|
|
|
|
break
|
|
|
|
case '.':
|
2017-09-11 10:04:48 +00:00
|
|
|
isV4 = true
|
2017-09-11 09:09:01 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !isV4 {
|
|
|
|
return ipv6ToUint64(ip)
|
|
|
|
}
|
|
|
|
return ipv4ToUint64(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
func ipv4ToUint64(s string) uint64 {
|
|
|
|
bits := strings.Split(s, ".")
|
|
|
|
|
|
|
|
b0, _ := strconv.Atoi(bits[0])
|
|
|
|
b1, _ := strconv.Atoi(bits[1])
|
|
|
|
b2, _ := strconv.Atoi(bits[2])
|
|
|
|
b3, _ := strconv.Atoi(bits[3])
|
|
|
|
|
|
|
|
var sum uint64
|
|
|
|
|
|
|
|
// left shifting 24,16,8,0 and bitwise OR
|
|
|
|
|
|
|
|
sum += uint64(b0) << 24
|
|
|
|
sum += uint64(b1) << 16
|
|
|
|
sum += uint64(b2) << 8
|
|
|
|
sum += uint64(b3)
|
|
|
|
|
|
|
|
return sum
|
|
|
|
}
|
|
|
|
|
|
|
|
func ipv6ToUint64(s string) uint64 {
|
|
|
|
bits := strings.Split(s, ":")
|
|
|
|
|
|
|
|
b0, _ := strconv.Atoi(bits[0])
|
|
|
|
b1, _ := strconv.Atoi(bits[1])
|
|
|
|
b2, _ := strconv.Atoi(bits[2])
|
|
|
|
b3, _ := strconv.Atoi(bits[3])
|
|
|
|
|
|
|
|
var sum uint64
|
|
|
|
|
|
|
|
// left shifting 24,16,8,0 and bitwise OR
|
|
|
|
|
|
|
|
sum += uint64(b0) << 24
|
|
|
|
sum += uint64(b1) << 16
|
|
|
|
sum += uint64(b2) << 8
|
|
|
|
sum += uint64(b3)
|
|
|
|
|
|
|
|
return sum
|
|
|
|
}
|