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
+18.4k Golang : Send email with attachment
+8.4k Golang : Another camera capture GUI application with GTK and OpenCV
+8.1k Golang : Check if integer is power of four example
+13.7k Golang : convert(cast) string to float value
+17.2k Golang : Check if IP address is version 4 or 6
+13.4k Golang : reCAPTCHA example
+8.9k Golang : How to capture return values from goroutines?
+10k Golang : Print how to use flag for your application example
+7.5k Golang : Convert(cast) io.Reader type to string
+5.4k Clean up Visual Studio For Mac installation failed disk full problem
+5.3k Golang : What is StructTag and how to get StructTag's value?