0

In Go one can send UDP packets using net.Addr interface to specify the target endpoint. Some special addresses, e.g. :8080 and 0.0.0.0, sends packets using local loopback interface. When received, still on the same host, the message's net.Addr shows [::1]:8080 as source. What is the the easiest way to determine that the packet was sent and received by the same host?

Here's an example in the Go Playground. It shows 0.0.0.0:8080 (ipv4) instead of [::1]:8080.

PalSivertsen
  • 384
  • 2
  • 11
  • the std lib provides a function for that https://golang.org/pkg/net/#IP.Equal –  Aug 24 '18 at 17:00
  • Your playground code is explicitly sending to INADDR_ANY rather than 127.0.0.1, which is why you got back 0.0.0.0. And IPv6 is disabled in the playground (which is annoying). – Michael Hampton Aug 28 '18 at 19:00

2 Answers2

0

I ended up using net.Dial("udp", addr) and eminently closing the connection. Dial also resolves hostnames, which I also needed.

Would be nice to avoid creating a socket, but Dial works for now.

PalSivertsen
  • 384
  • 2
  • 11
-1

:8080 is not an address, it is a port number, typically used when testing your own http websites on Windows because on Windows you cannot easily use port 80, the actual http port. This will only use the loopback interface if you use localhost as the IP address.

The localhost address for IPv4 is 127.0.0.1 and for IPv6 it is ::1. The address 0.0.0.0 is usually used as a placeholder address to indicate, for example, listening on all IP addresses, see this question.

As mentioned in the comment, you can use net.IP.Equal to check if your peer is localhost. Just compare your address in question to 127.0.0.1 or to ::1, the net.IP.Equal function considers them equal.

gonutz
  • 5,087
  • 3
  • 22
  • 40
  • In this context an address is and endpoint address, which includes the port. `net.IP.Equal` compares two IP addresses. An IPv4 is never equal to an IPv6 address. – PalSivertsen Aug 28 '18 at 13:46