Search code examples
goip

golang distinguish IPv4 IPv6


For a program I'm working on, I have to check whether an IP (the IP which connects me to the Internet) is public or private. For that, I need to distinguish if an IP is IPv4 or IPv6.

I wanted to check it by the length of the IP:

conn, err := net.Dial("udp", "8.9.10.11:2342")
if err != nil {
    fmt.Println("Error", err)
}

localaddr := conn.LocalAddr()

addr, _ := net.ResolveUDPAddr("udp", localaddr.String())

ip := addr.IP

fmt.Println(ip)
fmt.Println(len(ip))

Well, my IP is 192.168.2.100, so IPv4, but len(ip) tells me that the length is 16 which would be IPv6. What is my mistake? Does any other method exist to distinguish between IPv4 and IPv6 which works always?


Solution

  • jimt's answer is correct, but fairly complicated. I would simply check ip.To4() != nil. Since the documentation says "if ip is not an IPv4 address, To4 returns nil" this condition should return true if and only if the address is an IPv4 address.