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
+6.7k Golang : Get expvar(export variables) to work with multiplexer
+9.5k Golang : Validate IPv6 example
+18.7k Unmarshal/Load CSV record into struct in Go
+7.6k Golang : get the current working directory of a running program
+10.9k Golang : How to transmit update file to client by HTTP request example
+5.2k Javascript : Change page title to get viewer attention
+14.5k How to automatically restart your crashed Golang server
+13.7k Generate salted password with OpenSSL example
+9.3k Android Studio : Indicate progression with ProgressBar example
+23.5k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+18.9k Golang : Read input from console line
+10.1k Golang : How to get quoted string into another string?