ZetCode

Go UDP

last modified November 19, 2026 Go 1.27

In this article we show how to work with UDP in Go. We write datagram servers and clients with the net package, see how UDP keeps message boundaries, handle lost packets with deadlines and retries, deal with the datagram size limit, match replies to requests and build a small metrics collector.

All examples in this article were compiled and run with Go 1.27.0 on Linux. The servers listen on the loopback address, so the examples need no network access. The client port numbers in some outputs are chosen by the operating system and differ from run to run.

UDP and the net package

UDP (User Datagram Protocol) sends independent messages called datagrams. Unlike TCP, it has no connection setup, no acknowledgements and no retransmission. A datagram arrives whole or not at all; datagrams may be lost, duplicated or arrive out of order, and nobody tells the sender. In return, UDP is simple and fast. DNS, NTP, DHCP, game servers, VoIP and metrics agents such as StatsD use it. The protocol is described in RFC 768.

The net package handles UDP with the network names udp, udp4 and udp6. A server calls net.ListenPacket, which returns a net.PacketConn; there is no Accept, because there are no connections to accept. The server reads datagrams with ReadFrom, which also returns the sender's address, and answers with WriteTo. A client usually calls net.Dial, which fixes the remote address so that plain Read and Write can be used. The socket article covers TCP.

A UDP server

The first server receives datagrams and sends each one back in upper case.

upper_server.go
package main

import (
    "fmt"
    "log"
    "net"
    "strings"
)

func main() {

    conn, err := net.ListenPacket("udp", "127.0.0.1:5050")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    fmt.Println("Listening on", conn.LocalAddr())

    buf := make([]byte, 1024)

    for {
        n, client, err := conn.ReadFrom(buf)
        if err != nil {
            log.Println(err)
            continue
        }

        msg := string(buf[:n])
        fmt.Printf("%d bytes from %v: %q\n", n, client, msg)

        reply := strings.ToUpper(msg)
        if _, err := conn.WriteTo([]byte(reply), client); err != nil {
            log.Println(err)
        }
    }
}

One loop serves all clients. Each ReadFrom call returns one datagram, whoever sent it.

conn, err := net.ListenPacket("udp", "127.0.0.1:5050")

net.ListenPacket binds a UDP socket to port 5050 of the loopback interface. From now on the operating system queues every datagram sent to this address.

n, client, err := conn.ReadFrom(buf)

ReadFrom blocks until a datagram arrives, copies it into buf and returns its size and the address of the sender.

if _, err := conn.WriteTo([]byte(reply), client); err != nil {

WriteTo sends a datagram to the given address. Without the sender's address the server would not know where to reply.

We start the server in one terminal and run the clients of the next two sections in another one. The output shows the server after both clients have run; the first datagram came from one client port, the other three from another.

$ go run upper_server.go
Listening on 127.0.0.1:5050
18 bytes from 127.0.0.1:57215: "an old silent pond"
18 bytes from 127.0.0.1:44800: "an old silent pond"
15 bytes from 127.0.0.1:44800: "a frog jumps in"
6 bytes from 127.0.0.1:44800: "splash"

A UDP client

The client sends one line of text and prints the reply.

upper_client.go
package main

import (
    "fmt"
    "log"
    "net"
)

func main() {

    conn, err := net.Dial("udp", "127.0.0.1:5050")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    if _, err := conn.Write([]byte("an old silent pond")); err != nil {
        log.Fatal(err)
    }

    buf := make([]byte, 1024)

    n, err := conn.Read(buf)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(buf[:n]))
}

net.Dial with the udp network sends no packet; it only picks a local port and remembers the remote address.

if _, err := conn.Write([]byte("an old silent pond")); err != nil {

Each Write call sends one datagram. A successful write only means that the datagram left our program; it does not mean that anyone received it.

n, err := conn.Read(buf)

Read returns one datagram. The buffer must be large enough for the biggest expected reply.

$ go run upper_client.go
AN OLD SILENT POND

Message boundaries

TCP is a stream: two writes can arrive as one read, and one write as two reads. UDP keeps the boundaries, so every write on one side matches one read on the other.

boundaries.go
package main

import (
    "fmt"
    "log"
    "net"
)

func main() {

    conn, err := net.Dial("udp", "127.0.0.1:5050")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    lines := []string{"an old silent pond", "a frog jumps in", "splash"}

    for _, line := range lines {
        if _, err := conn.Write([]byte(line)); err != nil {
            log.Fatal(err)
        }
    }

    buf := make([]byte, 1024)

    for range lines {
        n, err := conn.Read(buf)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%d bytes: %s\n", n, buf[:n])
    }
}

The client sends three datagrams in a row and only then reads the replies.

for range lines {
    n, err := conn.Read(buf)

Each read returns exactly one reply, never a mix of two. On the loopback interface the datagrams also arrive in order; over a real network this is not guaranteed.

$ go run boundaries.go
18 bytes: AN OLD SILENT POND
15 bytes: A FROG JUMPS IN
6 bytes: SPLASH

No server listening

UDP has no handshake, so dialing a port where nobody listens succeeds. The error shows up later, if at all.

refused.go
package main

import (
    "errors"
    "fmt"
    "log"
    "net"
    "syscall"
    "time"
)

func main() {

    conn, err := net.Dial("udp", "127.0.0.1:5051")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    if _, err := conn.Write([]byte("hello")); err != nil {
        log.Fatal(err)
    }

    conn.SetReadDeadline(time.Now().Add(2 * time.Second))

    buf := make([]byte, 1024)
    _, err = conn.Read(buf)
    fmt.Println(err)

    if errors.Is(err, syscall.ECONNREFUSED) {
        fmt.Println("no server is listening on port 5051")
    }
}

The write succeeds too. The receiving host answers with an ICMP port unreachable message, and the operating system reports it on the next read.

conn.SetReadDeadline(time.Now().Add(2 * time.Second))

A read deadline makes Read give up at the given time. Without it, a read whose reply never comes blocks forever.

if errors.Is(err, syscall.ECONNREFUSED) {

The refused error is only delivered to a socket created with Dial, and only if the ICMP message reaches us. Firewalls often drop it, so a program must not rely on it; a missing server usually looks the same as a lost packet: no reply before the deadline.

$ go run refused.go
read udp 127.0.0.1:49230->127.0.0.1:5051: read: connection refused
no server is listening on port 5051

A lossy server

To test how a client copes with lost packets, we need a server that loses them on purpose. This one answers only every third datagram.

lossy_server.go
package main

import (
    "fmt"
    "log"
    "net"
    "strings"
)

func main() {

    conn, err := net.ListenPacket("udp", "127.0.0.1:5050")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    buf := make([]byte, 1024)
    count := 0

    for {
        n, client, err := conn.ReadFrom(buf)
        if err != nil {
            log.Println(err)
            continue
        }

        count++
        msg := string(buf[:n])

        if count%3 != 0 {
            fmt.Printf("dropped %q\n", msg)
            continue
        }

        fmt.Printf("answered %q\n", msg)
        reply := strings.ToUpper(msg)
        if _, err := conn.WriteTo([]byte(reply), client); err != nil {
            log.Println(err)
        }
    }
}

The server counts the datagrams it receives and silently ignores two of every three. From the client's side, this is the same as a datagram lost on the network.

if count%3 != 0 {
    fmt.Printf("dropped %q\n", msg)
    continue
}

The dropped datagrams get no reply. The output shows the server while the client of the next section ran.

$ go run lossy_server.go
dropped "first"
dropped "first"
answered "first"
dropped "second"
dropped "second"
answered "second"

Timeouts and retries

Since UDP does not retransmit, the application must. The client sends a request, waits a short time for the reply and sends it again if none comes.

retry_client.go
package main

import (
    "errors"
    "fmt"
    "log"
    "net"
    "os"
    "time"
)

func request(conn net.Conn, msg string, attempts int) (string, error) {

    buf := make([]byte, 1024)

    for i := 1; i <= attempts; i++ {

        if _, err := conn.Write([]byte(msg)); err != nil {
            return "", err
        }

        conn.SetReadDeadline(time.Now().Add(300 * time.Millisecond))

        n, err := conn.Read(buf)
        if err == nil {
            return string(buf[:n]), nil
        }

        if !errors.Is(err, os.ErrDeadlineExceeded) {
            return "", err
        }

        fmt.Printf("attempt %d: no reply\n", i)
    }

    return "", fmt.Errorf("no reply after %d attempts", attempts)
}

func main() {

    conn, err := net.Dial("udp", "127.0.0.1:5050")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    for _, msg := range []string{"first", "second"} {

        reply, err := request(conn, msg, 5)
        if err != nil {
            log.Fatal(err)
        }

        fmt.Println("reply:", reply)
    }
}

The request function tries up to attempts times and returns the first reply.

conn.SetReadDeadline(time.Now().Add(300 * time.Millisecond))

A deadline is an absolute point in time, so it is set again before every read.

if !errors.Is(err, os.ErrDeadlineExceeded) {
    return "", err
}

A timeout is expected and leads to the next attempt; any other error ends the request. Each message needs three attempts against the lossy server.

Retries are only safe if the request can be repeated, because the server may have received the earlier copy and only the reply was lost. Real protocols also wait longer after each failed attempt, so that a busy server is not flooded with copies.

$ go run retry_client.go
attempt 1: no reply
attempt 2: no reply
reply: FIRST
attempt 1: no reply
attempt 2: no reply
reply: SECOND

Datagram size

A UDP datagram holds at most 65507 bytes of data over IPv4. When the reader's buffer is smaller than the datagram, the rest is lost.

datagram_size.go
package main

import (
    "bytes"
    "fmt"
    "log"
    "net"
    "syscall"
)

func main() {

    addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:5052")
    if err != nil {
        log.Fatal(err)
    }

    server, err := net.ListenUDP("udp", addr)
    if err != nil {
        log.Fatal(err)
    }
    defer server.Close()

    client, err := net.DialUDP("udp", nil, addr)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    _, err = client.Write(make([]byte, 70000))
    fmt.Println("70000 bytes:", err)

    payload := bytes.Repeat([]byte("abcdefghij"), 10)
    if _, err := client.Write(payload); err != nil {
        log.Fatal(err)
    }

    buf := make([]byte, 16)

    n, _, flags, _, err := server.ReadMsgUDP(buf, nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("sent %d bytes, read %d: %s\n", len(payload), n, buf[:n])

    if flags&syscall.MSG_TRUNC != 0 {
        fmt.Println("the datagram was truncated")
    }
}

The program creates both ends itself. It uses net.ListenUDP and net.DialUDP, which return a *net.UDPConn with UDP-specific methods.

_, err = client.Write(make([]byte, 70000))

A datagram larger than the limit is rejected at once with a message too long error.

n, _, flags, _, err := server.ReadMsgUDP(buf, nil)

The server reads the 100-byte datagram into a 16-byte buffer. A plain Read would return 16 bytes with no error, and the remaining 84 bytes would be gone. ReadMsgUDP also returns the message flags, and on Linux syscall.MSG_TRUNC marks a truncated datagram.

In practice, datagrams should be smaller than the path MTU, about 1500 bytes on Ethernet minus the IP and UDP headers. Larger datagrams are split into IP fragments, and losing any fragment loses the whole datagram.

$ go run datagram_size.go
70000 bytes: write udp 127.0.0.1:60095->127.0.0.1:5052: write: message too long
sent 100 bytes, read 16: abcdefghijabcdef
the datagram was truncated

Tracking clients

UDP has no connections, so a server that keeps state per client must key it by the sender's address.

counter_server.go
package main

import (
    "fmt"
    "log"
    "net"
)

func main() {

    conn, err := net.ListenPacket("udp", "127.0.0.1:5050")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    counts := make(map[string]int)
    buf := make([]byte, 1024)

    for {
        n, client, err := conn.ReadFrom(buf)
        if err != nil {
            log.Println(err)
            continue
        }

        key := client.String()
        counts[key]++

        reply := fmt.Sprintf("%s: message %d from %s", buf[:n], counts[key], key)
        fmt.Println(reply)

        if _, err := conn.WriteTo([]byte(reply), client); err != nil {
            log.Println(err)
        }
    }
}

The server counts the messages from each client and puts the number into the reply.

key := client.String()
counts[key]++

The address string, such as 127.0.0.1:6001, identifies the client. A real server must also remove old entries, because it never learns that a client has gone away. The output shows the server while the client of the next section ran.

$ go run counter_server.go
hello: message 1 from 127.0.0.1:6001
hello: message 1 from 127.0.0.1:6002
how are you: message 2 from 127.0.0.1:6001
bye: message 3 from 127.0.0.1:6001
bye: message 2 from 127.0.0.1:6002

Clients on fixed ports

To see that the server tells clients apart by address, the next program opens two sockets bound to fixed local ports.

two_clients.go
package main

import (
    "fmt"
    "log"
    "net"
)

func dial(localPort int) *net.UDPConn {

    local := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: localPort}
    remote := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 5050}

    conn, err := net.DialUDP("udp", local, remote)
    if err != nil {
        log.Fatal(err)
    }

    return conn
}

func send(conn *net.UDPConn, msg string) {

    if _, err := conn.Write([]byte(msg)); err != nil {
        log.Fatal(err)
    }

    buf := make([]byte, 1024)

    n, err := conn.Read(buf)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(buf[:n]))
}

func main() {

    alice := dial(6001)
    defer alice.Close()

    bob := dial(6002)
    defer bob.Close()

    send(alice, "hello")
    send(bob, "hello")
    send(alice, "how are you")
    send(alice, "bye")
    send(bob, "bye")
}

The program talks to the server as two clients, alice and bob.

local := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: localPort}
remote := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 5050}

conn, err := net.DialUDP("udp", local, remote)

net.DialUDP accepts a local address. Usually it is nil and the operating system chooses a free port; here we choose ports 6001 and 6002, so the output is the same on every run.

$ go run two_clients.go
hello: message 1 from 127.0.0.1:6001
hello: message 1 from 127.0.0.1:6002
how are you: message 2 from 127.0.0.1:6001
bye: message 3 from 127.0.0.1:6001
bye: message 2 from 127.0.0.1:6002

A slow server

Retries create a new problem: a reply can arrive late, after the client has already sent the next copy. To show this, the server delays its first reply by half a second, longer than the client waits.

slow_server.go
package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
    "log"
    "net"
    "time"
)

func main() {

    conn, err := net.ListenPacket("udp", "127.0.0.1:5050")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    buf := make([]byte, 1024)
    count := 0

    for {
        n, client, err := conn.ReadFrom(buf)
        if err != nil {
            log.Println(err)
            continue
        }

        if n < 4 {
            fmt.Println("short datagram ignored")
            continue
        }

        count++
        id := binary.BigEndian.Uint32(buf[:4])
        fmt.Printf("request %d: %s\n", id, buf[4:n])

        if count == 1 {
            time.Sleep(500 * time.Millisecond)
        }

        reply := binary.BigEndian.AppendUint32(nil, id)
        reply = append(reply, bytes.ToUpper(buf[4:n])...)

        if _, err := conn.WriteTo(reply, client); err != nil {
            log.Println(err)
        }
    }
}

The messages now start with a 4-byte request ID in big-endian order. The server copies the ID into the reply, so the client can tell which request it answers.

id := binary.BigEndian.Uint32(buf[:4])

The encoding/binary package decodes the ID; the socket article uses the same technique for length prefixes. Datagrams shorter than four bytes are ignored.

reply := binary.BigEndian.AppendUint32(nil, id)
reply = append(reply, bytes.ToUpper(buf[4:n])...)

The reply starts with the same ID. The output shows the server while the client of the next section ran: the first message arrived twice under two different IDs.

$ go run slow_server.go
request 1: first
request 2: first
request 3: second

Request IDs

The client gives every attempt a new ID and accepts only the reply with the current one.

id_client.go
package main

import (
    "encoding/binary"
    "errors"
    "fmt"
    "log"
    "net"
    "os"
    "time"
)

var nextID uint32

func request(conn net.Conn, msg string, attempts int) (string, error) {

    buf := make([]byte, 1024)

    for range attempts {

        nextID++
        id := nextID

        req := binary.BigEndian.AppendUint32(nil, id)
        req = append(req, msg...)

        if _, err := conn.Write(req); err != nil {
            return "", err
        }

        conn.SetReadDeadline(time.Now().Add(300 * time.Millisecond))

        for {
            n, err := conn.Read(buf)
            if errors.Is(err, os.ErrDeadlineExceeded) {
                fmt.Printf("request %d: no reply\n", id)
                break
            }
            if err != nil {
                return "", err
            }

            if n < 4 {
                continue
            }

            got := binary.BigEndian.Uint32(buf[:4])
            if got != id {
                fmt.Printf("request %d: discarded reply %d\n", id, got)
                continue
            }

            return string(buf[4:n]), nil
        }
    }

    return "", fmt.Errorf("no reply after %d attempts", attempts)
}

func main() {

    conn, err := net.Dial("udp", "127.0.0.1:5050")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    for _, msg := range []string{"first", "second"} {

        reply, err := request(conn, msg, 3)
        if err != nil {
            log.Fatal(err)
        }

        fmt.Println("reply:", reply)
    }
}

The retry loop is the same as before, but a read may now return a reply to an older attempt.

nextID++
id := nextID

Each attempt gets a fresh ID. Reusing the ID of the first attempt would make the late reply look valid; here that would be harmless, but in a protocol where each request returns different data it would mix up the answers.

if got != id {
    fmt.Printf("request %d: discarded reply %d\n", id, got)
    continue
}

A reply with another ID is dropped, and the client keeps reading until the deadline. Request 1 timed out; while request 2 waited, the late reply to request 1 arrived and was discarded. DNS matches queries and answers with the same kind of ID.

$ go run id_client.go
request 1: no reply
request 2: discarded reply 1
reply: FIRST
reply: SECOND

A metrics collector

Fire-and-forget messages are a good fit for UDP: the sender does not wait for an answer, and losing a few of them does no harm. Metrics agents such as StatsD work this way. The server sums name:value lines and prints the totals every second.

metrics_server.go
package main

import (
    "fmt"
    "log"
    "maps"
    "net"
    "slices"
    "strconv"
    "strings"
    "time"
)

func main() {

    conn, err := net.ListenPacket("udp", "127.0.0.1:8125")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    lines := make(chan string)

    go func() {
        buf := make([]byte, 1500)
        for {
            n, _, err := conn.ReadFrom(buf)
            if err != nil {
                log.Println(err)
                continue
            }
            for line := range strings.Lines(string(buf[:n])) {
                lines <- strings.TrimSpace(line)
            }
        }
    }()

    totals := make(map[string]int)
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()

    for {
        select {
        case line := <-lines:
            name, value, ok := strings.Cut(line, ":")
            n, err := strconv.Atoi(value)
            if !ok || err != nil {
                fmt.Printf("bad metric %q\n", line)
                continue
            }
            totals[name] += n

        case <-ticker.C:
            if len(totals) == 0 {
                continue
            }
            var report []string
            for _, name := range slices.Sorted(maps.Keys(totals)) {
                report = append(report, fmt.Sprintf("%s=%d", name, totals[name]))
            }
            fmt.Println(strings.Join(report, " "))
            clear(totals)
        }
    }
}

A goroutine reads datagrams and passes their lines to the main loop through a channel. The main loop updates the totals and reports them on a timer, so the map is used by one goroutine only.

for line := range strings.Lines(string(buf[:n])) {
    lines <- strings.TrimSpace(line)
}

One datagram can carry several metrics, one per line. Packing them saves packets; it is safe as long as the datagram stays below the MTU, which is why the buffer has 1500 bytes.

case <-ticker.C:

Every second, the server prints the sorted totals and clears them. Bad lines are reported and skipped. The output shows two runs of the client of the next section, more than a second apart.

$ go run metrics_server.go
bad metric "errors:x"
bytes=60000 requests=200
bad metric "errors:x"
bytes=60000 requests=200

Sending metrics

The client sends metrics from four goroutines and never reads a reply.

metrics_client.go
package main

import (
    "fmt"
    "log"
    "net"
    "sync"
)

func main() {

    conn, err := net.Dial("udp", "127.0.0.1:8125")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    var wg sync.WaitGroup

    for worker := 1; worker <= 4; worker++ {
        wg.Go(func() {
            for i := range 50 {
                msg := fmt.Sprintf("requests:1\nbytes:%d\n", 100*(i%5+1))
                if _, err := conn.Write([]byte(msg)); err != nil {
                    log.Println(err)
                    return
                }
            }
        })
    }

    wg.Wait()

    if _, err := conn.Write([]byte("errors:x\n")); err != nil {
        log.Fatal(err)
    }

    fmt.Println("sent 201 datagrams")
}

The goroutines share one socket. This is safe: concurrent writes on a net.Conn are allowed, and each write is a separate datagram, so the messages cannot interleave.

msg := fmt.Sprintf("requests:1\nbytes:%d\n", 100*(i%5+1))

Each datagram carries two metrics. The four workers send 200 datagrams, and a final datagram holds an invalid value.

The totals show that no datagram was lost on the loopback interface. Under heavy load, the server's receive buffer can fill up and the kernel drops new datagrams without telling anyone; a collector must tolerate small gaps.

$ go run metrics_client.go
sent 201 datagrams

Source

Go net package - reference
Go encoding/binary package - reference
RFC 768 - User Datagram Protocol
RFC 8085 - UDP Usage Guidelines

In this article we have worked with UDP in Go: a datagram server and client, message boundaries, a refused port, retries against a lossy server, the datagram size limit, per-client state, request IDs and a metrics collector. The socket article covers TCP, and the HTTP server and HTTP client articles show the higher-level net/http package.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.