Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang distinguish IPv4 IPv6

Tags:

go

ip

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?

like image 489
user3479275 Avatar asked Mar 30 '14 22:03

user3479275


People also ask

How do I know if my IP is v4 or v6?

I would use . To4(), . To16() ,from the net package, to find if it is an IPv4 or IPv6 address.

Is IPv4 a Golang?

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.


1 Answers

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.

like image 137
Evan Avatar answered Sep 23 '22 13:09

Evan