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
+41.4k Golang : How to count duplicate items in slice/array?
+21.8k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+6.3k Apt-get to install and uninstall Golang
+6.3k Linux/Unix : Commands that you need to be careful about
+9.2k Golang : Intercept and compare HTTP response code example
+15.2k Golang : How do I get the local IP (non-loopback) address ?
+8.9k Golang : On lambda, anonymous, inline functions and function literals
+17.5k Golang : How to tell if a file is compressed either gzip or zip ?
+13.5k Golang : Get constant name from value
+8.8k Golang : How to join strings?
+23.1k Golang : Calculate time different
+18.6k Golang : Set, Get and List environment variables