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
+12.5k Golang : flag provided but not defined error
+5.3k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+17.2k Golang : How to tell if a file is compressed either gzip or zip ?
+9k Golang : How to use Gorilla webtoolkit context package properly
+11k Golang : Fix go.exe is not compatible with the version of Windows you're running
+6.8k Get Facebook friends working in same company
+15.9k Golang : Get file permission
+16.3k Golang : Convert slice to array
+18.1k Golang : Get command line arguments
+10.2k Golang : Convert file content to Hex
+8.9k Golang : Inject/embed Javascript before sending out to browser example
+13.1k Golang : Skip blank/empty lines in CSV file and trim whitespaces example