Golang : How to convert(cast) string to IP address?
Problem :
You have IP address in string type and you want to convert(cast) the string into type IP address.
Solution :
Use the net.ParseIP()
function to convert the string to type IP address (http://golang.org/pkg/net/#IP)
For example :
package main
import (
"fmt"
"net"
)
func main() {
// type string
str := "106.10.138.240"
// type IP
IPAddress := net.ParseIP(str)
fmt.Println("4-byte representation : ", IPAddress.To4())
// fmt.Println("16-byte representation : ", IPAddress.To16())
}
See also : Golang : How to convert(cast) IP address to string?
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
+10k Golang : Turn string or text file into slice example
+21.1k PHP : Convert(cast) int to double/float
+9.6k Golang : Qt Yes No and Quit message box example
+8.4k Prevent Write failed: Broken pipe problem during ssh session with screen command
+5.3k Responsive Google Adsense
+17k Golang : How to generate QR codes?
+22.6k Golang : Convert Unix timestamp to UTC timestamp
+33.8k Golang : How to check if slice or array is empty?
+7.5k Golang : Accessing dataframe-go element by row, column and name example
+5.9k Linux : Disable and enable IPv4 forwarding
+26.4k Golang : Calculate future date with time.Add() function
+6.8k Golang : Derive cryptographic key from passwords with Argon2