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 (

func main() {
	ip := net.ParseIP("")
	if ip == nil {
		fmt.Println("IP address is not valid")

	if ip.To4() != nil {
		fmt.Println("IP address is v4")
	} else {
		fmt.Println("IP address is v6")
1 email / week to learn how to (ab)use technology for fun & profit: Programming, Hacking & Entrepreneurship.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Tags: golang, programming, devops

Want to learn Rust, Cryptography and Security? Get my book Black Hat Rust!