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
+6.8k Swift : Convert (cast) String to Double
+20.5k Golang : Match strings by wildcard patterns with filepath.Match() function
+37.8k Golang : How to iterate over a []string(array)
+25.9k PHP : Count number of JSON items/objects
+5.7k Default cipher that OpenSSL used to encrypt a PEM file
+8.3k Golang : ffmpeg with os/exec.Command() returns non-zero status
+23.8k Golang : Convert uint value to string type
+6.7k Golang : Grayscale Image
+7.3k Swift : Convert (cast) Character to Integer?
+10.2k Golang : Simple file scaning and remove virus example
+32.4k Golang : How to check if slice or array is empty?
+13.7k Golang : How to check for empty array string or string?