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
+5.1k Golang : Scan forex opportunities by Bollinger bands
+37.8k Golang : Remove dashes(or any character) from string
+6.1k Golang : Check if one string(rune) is permutation of another string(rune)
+16.4k Golang : How to log each HTTP request to your web server?
+19.5k Golang : Clean up null characters from input data
+46.9k Golang : Upload file from web browser to server
+5.9k Golang : constant 20013 overflows byte error message
+10.5k Golang : Change date format to yyyy-mm-dd
+13.1k Golang : Find network of an IP address
+16.4k Convert JSON to CSV in Golang
+7.3k Golang : Convert word to its plural form example
+6.4k Golang : Lock executable to a specific machine with unique hash of the machine