#1732·dns

UDP ResponseWriter.LocalAddr() returns the wildcard address instead of the packet's destination IP

Author: Amila-RukshanCreated Sep 24, 2026Updated Sep 27, 2026

Problem

When a server listens on a wildcard address (0.0.0.0:53, [::]:53, or :53), ResponseWriter.LocalAddr() for UDP returns the socket's bound address (0.0.0.0 / ::), not the IP the query was actually sent to. TCP doesn't have this problem, because the accepted connection already carries the real local address.

This breaks CoreDNS features that depend on the server IP (https://github.com/coredns/coredns/issues/8497), e.g. server_ip() in view expressions and the {server_ip} placeholder in rewrite/log, when CoreDNS listens on all interfaces.

Reproduce

Listen on 0.0.0.0:0 (or [::]:0), send a query to 127.0.0.1, and log w.LocalAddr() in the handler:

Listen Query to LocalAddr() today Expected
0.0.0.0 127.0.0.1 [::] 127.0.0.1
[::] ::1 [::] ::1
[::] 127.0.0.1 [::] 127.0.0.1

The cause is different on each platform:

  • Linux (and the BSDs): udp.go already reads the destination address from the control messages (IP_PKTINFO), but only uses it to set the source address of the reply (correctSource). LocalAddr() ignores it and returns the socket address.
  • macOS: the destination address isn't available at all, because darwin uses udp_no_control.go, which discards the control messages.

Proposed fix

Forked repo: https://github.com/amila-rukshan/dns/commit/364075da78d2ce63b735a7bf0c718606b77113dd

  • server.go: for UDP, LocalAddr() returns the packet's destination IP (taken from the control messages the library already reads) plus the socket's port, and falls back to the socket address when that IP isn't available.
  • udp.go / udp_no_control.go: add SessionUDP.dst(). Darwin now uses udp.go, so it receives the destination address. Sending on darwin is unchanged: it still attaches no packet info, to avoid #724.
  • Windows is unchanged, since dst() returns nil there and LocalAddr() falls back to the socket address as before.
  • New test TestServingUDPLocalAddrWildcard, which fails before the change and passes after.

Behaviour change

For UDP, LocalAddr() now returns the address each query was sent to, not the listening address. That's the point of the fix, but anything comparing it to the listener address would see a different value.

Testing

  • Full suite with -race, before vs after: identical results on macOS and Linux (Docker, golang:1.25), apart from the new test.
  • go vet passes for linux, windows, freebsd, openbsd, android, js/wasm and darwin.
  • CoreDNS built against the branch: plugin tests pass, and server_ip() returns the correct IP.

I know v1 only takes specific fixes now. Happy to open a PR if you add me, or feel free to apply the patch directly.