Here, we will help you to understand how to parse IPv4 or IPv6 address in Go. We will learn about ParseIP() method of net package by example and program.
ParseIP() method of net package is used to parse IPv4 or IPv6 address in Go.
Function prototype:
func ParseIP(ip_addr string) IP
Input parameters:
ip_addr: string ip_addr can be in IPv4 dotted decimal (“10.10.10.2”), IPv6 (“2222:fb8::68”) or IPv4-mapped IPv6 (“::ffff:192.0.3.2”) form.
Return value:
ParseIP() function in net package returns IP address of type net.IP i.e It is a single IP address or a slice of bytes. If IP address format is incorrect, It returns nil.
Example with code:
package main
import (
"fmt"
"net"
"reflect"
)
func main() {
ip := net.ParseIP("192.0.2.2")
if ip != nil {
fmt.Println("Ip address: ", ip)
fmt.Println("Type: ", reflect.TypeOf(ip))
} else {
fmt.Println("Invalid IP address", ip)
}
}
Output:
$ go run sample.go
Ip address: 192.0.2.2
Type: net.IP
Example with Invalid IP address:
package main
import (
"fmt"
"net"
"reflect"
)
func main() {
// Invalid IP address
ip := net.ParseIP("192.0.2.2456")
if ip != nil {
fmt.Println("Ip address: ", ip)
fmt.Println("Type: ", reflect.TypeOf(ip))
} else {
fmt.Println("Invalid IP address", ip)
}
}
Output:
$: go run sample.go
Invalid IP address <nil>
To learn more about golang, Please refer given below link:
https://www.techieindoor.com/go-lang-tutorial/
References:
https://golang.org/doc/ https://golang.org