Check if an IP address is IPV4 or IPV6 in Go
Once you have successfully parsed an IP address in Go with net.ParseIP
you may want to distinguish if the IP is a v4
or a v6
address.
For that you can simply use the IP.To4
function which returns nil
if the IP address is not a v4
address (and thus is a v6
address).
Here is a complete code example:
package main
import (
"fmt"
"net"
)
func main() {
ip := net.ParseIP("127.0.0.1")
if ip == nil {
fmt.Println("IP address is not valid")
return
}
if ip.To4() != nil {
fmt.Println("IP address is v4")
} else {
fmt.Println("IP address is v6")
}
}