47 lines
895 B
Go
47 lines
895 B
Go
package converter
|
|
|
|
import (
|
|
"net"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func IP4toInt(IPv4Addr net.IP) int64 {
|
|
return StrToInt(IPv4Addr.String())
|
|
}
|
|
|
|
func StrToInt(strIp string) int64 {
|
|
bits := strings.Split(strIp, ".")
|
|
|
|
b0, _ := strconv.Atoi(bits[0])
|
|
b1, _ := strconv.Atoi(bits[1])
|
|
b2, _ := strconv.Atoi(bits[2])
|
|
b3, _ := strconv.Atoi(bits[3])
|
|
|
|
var sum int64
|
|
|
|
// left shifting 24,16,8,0 and bitwise OR
|
|
|
|
sum += int64(b0) << 24
|
|
sum += int64(b1) << 16
|
|
sum += int64(b2) << 8
|
|
sum += int64(b3)
|
|
|
|
return sum
|
|
}
|
|
|
|
func IntToIP4(ipInt int64) net.IP {
|
|
|
|
//return b0 + "." + b1 + "." + b2 + "." + b3
|
|
return net.ParseIP(IntToStr(ipInt))
|
|
}
|
|
|
|
func IntToStr(ipInt int64) string {
|
|
b0 := strconv.FormatInt((ipInt>>24)&0xff, 10)
|
|
b1 := strconv.FormatInt((ipInt>>16)&0xff, 10)
|
|
b2 := strconv.FormatInt((ipInt>>8)&0xff, 10)
|
|
b3 := strconv.FormatInt((ipInt & 0xff), 10)
|
|
|
|
return b0 + "." + b1 + "." + b2 + "." + b3
|
|
}
|