Golang : Convert decimal number(integer) to IPv4 address
Problem :
You've read the previous tutorial on how to convert IPv4 address to decimal number and store into database. However, now you want to convert the decimal value back to IPv4 address. How to do that?
Solution :
Reverse the algorithm used in the conversion to decimal number. However, to get the correct result, we need to do two bit shifting and “0xff” masking.
For example :
package main
import (
"fmt"
"strconv"
)
func InttoIP4(ipInt int64) string {
// need to do two bit shifting and “0xff” masking
b0 := strconv.FormatInt((ipInt>>24)&0xff, 10)
b1 := strconv.FormatInt((ipInt>>16)&0xff, 10)
b2 := strconv.FormatInt((ipInt>>8)&0xff, 10)
b3 := strconv.FormatInt((ipInt & 0xff), 10)
return b0 + "." + b1 + "." + b2 + "." + b3
}
func main() {
// 1653276013 = 98.138.253.109
IPv4 := InttoIP4(1653276013)
fmt.Println(IPv4)
}
Output :
98.138.253.109
References :
https://processing.org/reference/bitwiseOR.html
http://stackoverflow.com/questions/12130464/ip-address-conversion-to-decimal-and-vice-versa
See also : Golang : Convert IPv4 address to decimal number(base 10) or integer
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
+4.4k Golang : Detect words using using consecutive letters in a given string
+8.9k Golang : Channels and buffered channels examples
+19.4k Golang : Convert PNG transparent background image to JPG or JPEG image
+8.9k Golang : Setting variable value with ldflags
+18.4k Swift : Convert (cast) Int to int32 or Uint32
+17.8k Golang : Get RGBA values of each image pixel
+13.4k Golang : Get URI segments by number and assign as variable example
+11.7k Golang : Convert(cast) uintptr to string example
+9.3k Golang : Generate random integer or float number
+9.1k Golang : Read file and convert content to string
+12.8k Android Studio : Use image as AlertDialog title with custom layout example
+16.1k Golang : How to make a file read only and set it to writable again?