Golang : Convert IP address string to long ( unsigned 32-bit integer )
Here is another way of converting IPv4 string to long ( unsigned 32-bit integer ). Pretty similar to the previous tutorial on how to convert IPv4 address to base 10.
Here you go!
package main
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"strconv"
)
func ip2Long(ip string) uint32 {
var long uint32
binary.Read(bytes.NewBuffer(net.ParseIP(ip).To4()), binary.BigEndian, &long)
return long
}
func backtoIP4(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() {
result := ip2Long("98.138.253.109")
fmt.Println(result)
// or if you prefer the super fast way
faster := binary.BigEndian.Uint32(net.ParseIP("98.138.253.109")[12:16])
fmt.Println(faster)
faster64 := int64(faster)
fmt.Println(backtoIP4(faster64))
}
Output:
1653276013
1653276013
98.138.253.109
References:
https://www.socketloop.com/tutorials/golang-convert-decimal-number-integer-to-ipv4-address
See also : Golang : How to check if IP address is in range
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
+32.7k Golang : How to check if a date is within certain range?
+8.3k PHP : How to parse ElasticSearch JSON ?
+8.2k Golang : How to check variable or object type during runtime?
+5.2k Unix/Linux/MacOSx : How to remove an environment variable ?
+12.7k Golang : Convert IPv4 address to packed 32-bit binary format
+7.7k Golang Hello World Example
+23.3k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+5.1k Javascript : Shuffle or randomize array example
+10.8k Golang : Simple image viewer with Go-GTK
+17.7k Golang : Get all upper case or lower case characters from string example
+5.1k Golang : Get FX sentiment from website example
+10.3k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?