diff --git a/net/converter/ip.go b/net/converter/ip.go new file mode 100644 index 0000000..bf86b0b --- /dev/null +++ b/net/converter/ip.go @@ -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 +}