From dca6bfc1c261a4993298d644faa0a413d5650e95 Mon Sep 17 00:00:00 2001 From: Bryan Bess Date: Tue, 4 Oct 2022 08:28:00 -0500 Subject: [PATCH] Use ListenPacket instead of Dial for UDP --- statsd/udp.go | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/statsd/udp.go b/statsd/udp.go index e2922a911..414255ab9 100644 --- a/statsd/udp.go +++ b/statsd/udp.go @@ -7,26 +7,27 @@ import ( // udpWriter is an internal class wrapping around management of UDP connection type udpWriter struct { - conn net.Conn + conn net.PacketConn + addr string } // New returns a pointer to a new udpWriter given an addr in the format "hostname:port". func newUDPWriter(addr string, _ time.Duration) (*udpWriter, error) { - udpAddr, err := net.ResolveUDPAddr("udp", addr) + conn, err := net.ListenPacket("udp", ":0") if err != nil { return nil, err } - conn, err := net.DialUDP("udp", nil, udpAddr) - if err != nil { - return nil, err - } - writer := &udpWriter{conn: conn} + writer := &udpWriter{conn: conn, addr: addr} return writer, nil } // Write data to the UDP connection with no error handling func (w *udpWriter) Write(data []byte) (int, error) { - return w.conn.Write(data) + dst, err := net.ResolveUDPAddr("udp", w.addr) + if err != nil { + return 0, err + } + return w.conn.WriteTo(data, dst) } func (w *udpWriter) Close() error {