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
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+9.7k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+9.1k Golang : How to protect your source code from client, hosting company or hacker?
+48.2k Golang : Upload file from web browser to server
+18.4k Unmarshal/Load CSV record into struct in Go
+24.1k Golang : GORM read from database example
+5.9k Java : Human readable password generator
+5.7k Golang : Shuffle array of list
+10.5k Golang : Get currencies exchange rates example
+32.5k Golang : How to check if a date is within certain range?
+7.7k Golang : Check from web if Go application is running or not
+7.1k Golang : How to convert strange string to JSON with json.MarshalIndent