ip
This commit is contained in:
parent
ad1838bb69
commit
5db26291ed
64
net/converter/ip.go
Normal file
64
net/converter/ip.go
Normal file
|
@ -0,0 +1,64 @@
|
|||
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 = false
|
||||
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
|
||||
}
|
Loading…
Reference in New Issue
Block a user