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
+20.4k Golang : Convert date string to variants of time.Time type examples
+12.6k Golang : Convert IPv4 address to packed 32-bit binary format
+18.5k Golang : Delete duplicate items from a slice/array
+5.4k Golang : Frobnicate or tweaking a string example
+10.2k Golang : Create matrix with Gonum Matrix package example
+24.1k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+21.3k Golang : Convert string slice to struct and access with reflect example
+28.8k Golang : Saving(serializing) and reading file with GOB
+4.6k Javascript : How to get width and height of a div?
+8.5k Golang : Accept any number of function arguments with three dots(...)
+21.8k Golang : How to run Golang application such as web server in the background or as daemon?
+9.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases