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?
I would use . To4(), . To16() ,from the net package, to find if it is an IPv4 or IPv6 address.
The IPv4 function of the net package in Golang returns a 16-byte IP object that corresponds to a given set of bytes that represent an IPv4 address.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With