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
+19.7k Curl usage examples with Golang
+11.2k Golang : Listen and Serve on sub domain example
+6k Golang : Transform lisp or spinal case to Pascal case example
+4.6k Unix/Linux/MacOSx : Get local IP address
+18.8k Golang : Read directory content with os.Open
+8.4k Golang : How to protect your source code from client, hosting company or hacker?
+16.7k Golang : Get command line arguments
+12.6k Golang : How to determine if a year is leap year?
+3.9k Golang : A program that contain another program and executes it during run-time
+4.6k Golang : What is StructTag and how to get StructTag's value?
+3.8k Golang : Experimental Jawi programming language
+6.7k Golang : Reverse a string with unicode