All Articles

How to convert IPv4 and IPv6 to integer

Sometimes we need to convert IPv4/IPv6 to integer/decimal for storing purposes. It allows the creation of more efficient database indexes and filter values faster.

Here is how we could do it in a few lines of code in golang:

package main import ( "fmt" "math/big" "net" ) func Ip2Int(ip net.IP) *big.Int { i := big.NewInt(0) i.SetBytes(ip) return i } func main() { fmt.Println(Ip2Int(net.ParseIP("20.36.77.12")).String()) fmt.Println(Ip2Int(net.ParseIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).String()) }

Play with code

Share your thoughts 😉

Happy coding! 🚀