util/net/converter/ip.go

65 lines
1.0 KiB
Go
Raw Normal View History

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)
}
2017-11-10 07:05:28 +00:00
return IPV4ToUint64(ip)
2017-09-11 09:09:01 +00:00
}
2017-11-10 07:05:28 +00:00
func IPV4ToUint64(s string) uint64 {
2017-09-11 09:09:01 +00:00
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
}