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
+5.6k Golang : Launching your executable inside a console under Linux
+7.3k Golang : Dealing with struct's private part
+15.3k Golang : rune literal not terminated error
+16.8k Golang : Get number of CPU cores
+14.2k Golang : How to check if your program is running in a terminal
+8.7k Golang : Sort lines of text example
+18.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+14.3k Golang : Missing Bazaar command
+9.9k Golang : Edge detection with Sobel method
+7.4k Golang : Convert(cast) io.Reader type to string
+8.4k Golang : Progress bar with ∎ character