65 lines
1.0 KiB
Go
65 lines
1.0 KiB
Go
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 '.':
|
|
isV4 = true
|
|
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
|
|
}
|