UDP Echo Server and Client

A connectionless echo over UDP. The server reads one datagram with ReadFrom and writes it straight back to the sender's address. The client dials, fires one datagram, and reads the echo under a deadline so it never hangs.

package main

import (
	"fmt"
	"net"
	"time"
)

func main() {
	pc, err := net.ListenPacket("udp", "127.0.0.1:0")
	if err != nil {
		fmt.Println("listen:", err)
		return
	}
	defer pc.Close()
	fmt.Println("udp server on", pc.LocalAddr())

	// Server: read one datagram, echo it back to whoever sent it.
	go func() {
		buf := make([]byte, 1024)
		n, addr, err := pc.ReadFrom(buf)
		if err != nil {
			return
		}
		fmt.Printf("server got %q from %s\n", buf[:n], addr)
		pc.WriteTo(buf[:n], addr)
	}()

	// Client: send a datagram, wait up to 2s for the echo.
	conn, err := net.Dial("udp", pc.LocalAddr().String())
	if err != nil {
		fmt.Println("dial:", err)
		return
	}
	defer conn.Close()

	fmt.Fprint(conn, "ping over udp")
	conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	reply := make([]byte, 1024)
	n, err := conn.Read(reply)
	if err != nil {
		fmt.Println("read:", err)
		return
	}
	fmt.Printf("client got %q\n", reply[:n]) // client got "ping over udp"
}

Save the code as main.go and run it:

go run main.go

Expected output:

udp server on 127.0.0.1:51275
server got "ping over udp" from 127.0.0.1:61757
client got "ping over udp"

Both ports are OS-assigned, so the numbers will differ each run.

💻 Run locally

Copy the code above and run it on your machine

© 2026 ByteLearn.dev. Free courses for developers. · Privacy