Golang : Convert IPv4 address to packed 32-bit binary format
There are times when we need to deal with low-level network functions such as dealing with C program and the IP version 4 string address format is not really suitable. The IP version 4 address needs to be converted to packed 32-bit binary format first.
For example,
IP address 127.0.0.1 packed to 7f000001
Below is an example on how to convert the IPv4 address to packed 32-bits with encoding/binary
package.
Here you go!
package main
import (
"bytes"
"encoding/binary"
"fmt"
"math/big"
"net"
)
func IP4toInt(IPv4Address net.IP) int64 {
IPv4Int := big.NewInt(0)
IPv4Int.SetBytes(IPv4Address.To4())
return IPv4Int.Int64()
}
//similar to Python's socket.inet_aton() function
//https://docs.python.org/3/library/socket.html#socket.inet_aton
func Pack32BinaryIP4(ip4Address string) string {
ipv4Decimal := IP4toInt(net.ParseIP(ip4Address))
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.BigEndian, uint32(ipv4Decimal))
if err != nil {
fmt.Println("Unable to write to buffer:", err)
}
// present in hexadecimal format
result := fmt.Sprintf("%x", buf.Bytes())
return result
}
func main() {
fmt.Println("IP address 127.0.0.1 packed to ", Pack32BinaryIP4("127.0.0.1"))
fmt.Println("IP address 192.168.0.1 packed to ", Pack32BinaryIP4("192.168.0.1"))
}
Output:
IP address 127.0.0.1 packed to 7f000001
IP address 192.168.0.1 packed to c0a80001
Happy coding!
References:
https://www.socketloop.com/tutorials/golang-convert-decimal-number-integer-to-ipv4-address
https://golang.org/pkg/encoding/binary/#Write
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
+6.4k Golang : Output or print out JSON stream/encoded data
+8.5k Golang : Combine slices but preserve order example
+18.3k Golang : Display list of time zones with GMT
+4.8k Golang : Check if a word is countable or not
+45.6k Golang : Read tab delimited file with encoding/csv package
+11.3k Golang : Display a text file line by line with line number example
+9.4k Golang : Qt get screen resolution and display on center example
+16.8k Golang : How to tell if a file is compressed either gzip or zip ?
+7k Golang : How to iterate a slice without using for loop?
+6.3k Golang : Totalize or add-up an array or slice example
+6.9k CloudFlare : Another way to get visitor's real IP address
+6.7k Golang : How to call function inside template with template.FuncMap