Golang : Convert IPv4 address to decimal number(base 10) or integer
Problem :
IP address in decimal is easier to search, filter or compare. For example, searching for IP address in a given range.
You want to convert IPv4 address to integer to perform bitwise operation or for efficient storage in a database. How to do that?
Solutions :
package main
import (
"fmt"
"net"
"strconv"
"strings"
)
func IP4toInt(IPv4Addr net.IP) int64 {
bits := strings.Split(IPv4Addr.String(), ".")
b0, _ := strconv.Atoi(bits[0])
b1, _ := strconv.Atoi(bits[1])
b2, _ := strconv.Atoi(bits[2])
b3, _ := strconv.Atoi(bits[3])
var sum int64
// left shifting 24,16,8,0 and bitwise OR
sum += int64(b0) << 24
sum += int64(b1) << 16
sum += int64(b2) << 8
sum += int64(b3)
return sum
}
func main() {
ipDecimal := IP4toInt(net.ParseIP("98.138.253.109"))
fmt.Println(ipDecimal)
}
Output :
1653276013
Is there an easier way? Of course! See this next example :
package main
import (
"fmt"
"math/big"
"net"
)
func IP4toInt(IPv4Address net.IP) int64 {
IPv4Int := big.NewInt(0)
IPv4Int.SetBytes(IPv4Address.To4())
return IPv4Int.Int64()
}
func main() {
ipv4Decimal := IP4toInt(net.ParseIP("98.138.253.109"))
fmt.Println(ipv4Decimal)
}
Output :
1653276013
Happy coding!
References :
https://www.socketloop.com/tutorials/golang-how-to-convert-cast-string-to-ip-address
See also : Golang : Convert decimal number(integer) to IPv4 address
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
+19k Golang : How to Set or Add Header http.ResponseWriter?
+6.1k Golang : Calculate diameter, circumference, area, sphere surface and volume
+8k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+8.6k Golang : Capture text return from exec function example
+8.1k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+18.3k Golang : Check whether a network interface is up on your machine
+23.3k Golang : Upload to S3 with official aws-sdk-go package
+26.1k Golang : Convert file content into array of bytes
+21.3k Golang : How to reverse slice or array elements order
+19.5k Golang : Check if os.Stdin input data is piped or from terminal
+17.9k Golang : Read binary file into memory
+19.3k Golang : How to get time from unix nano example