Golang : Convert IP version 6 address to integer or decimal number
Problem :
You have IP address version 6 in string format and you want to convert it into integer. How to do that?
NOTE : IP address in decimal number format is easier to search, filter or compare. For example, searching for IP address in a given range.
Solution :
Use math/big.Int.SetBytes()
to convert the IPv6 address to a signed multi-precision integer.
package main
import (
"fmt"
"math/big"
"net"
)
func IP6toInt(IPv6Address net.IP) *big.Int {
IPv6Int := big.NewInt(0)
// from http://golang.org/pkg/net/#pkg-constants
// IPv6len = 16
IPv6Int.SetBytes(IPv6Address.To16())
return IPv6Int
}
func main() {
ipv6Decimal := IP6toInt(net.ParseIP("FE80::0202:B3FF:FE1E:8329"))
fmt.Println(ipv6Decimal)
}
Output :
338288524927261089654163772891438416681
References :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.6k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+3.4k Javascript : Empty an array example
+4.7k Javascript : Shuffle or randomize array example
+4.3k Golang : Display packages names during compilation
+6.6k Golang : How to stop user from directly running an executable file?
+12.7k Golang : Activate web camera and broadcast out base64 encoded images
+4k Unix/Linux : How to pipe/save output of a command to file?
+61.7k Golang : Convert HTTP Response body to string
+19.7k Golang : Convert date string to variants of time.Time type examples
+15.9k Golang : Capture stdout of a child process and act according to the result
+26.9k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+6.9k Gogland : Where to put source code files in package directory for rookie