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
+13.4k Golang : Read from buffered reader until specific number of bytes
+11.5k CodeIgniter : Import Linkedin data
+9.5k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+10.5k Swift : Convert (cast) String to Integer
+16.1k Golang : How to check if input from os.Args is integer?
+18k Golang : How to log each HTTP request to your web server?
+7.1k Golang : Squaring elements in array
+9.6k Golang : Quadratic example
+8k Golang : Sort words with first uppercase letter
+20.7k Android Studio : AlertDialog and EditText to get user string input example
+46.5k Golang : Encode image to base64 example
+41.4k Golang : Convert string to array/slice