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
+11k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+7.6k Golang : Generate human readable password
+9.8k Golang : Check if user agent is a robot or crawler example
+13.4k Facebook PHP getUser() returns 0
+30.6k Golang : Download file example
+19.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+12.1k Golang : calculate elapsed run time
+13.3k Golang : Read from buffered reader until specific number of bytes
+16.9k Golang : How to save log messages to file?
+23k Golang : Print out struct values in string format
+7.4k SSL : How to check if current certificate is sha1 or sha2 from command line
+24.2k Golang : How to validate URL the right way