Learn more about Israeli war crimes in Gaza, funded by the USA, Germany, the UK and others.

How do I write a UDP server in Go?

Discovered how simple UDP is. Here is a client and server written in Go. (Error handling omitted for brevity.)

First a server. It listens for UDP packets on port 10001, and prints each message to stdout:

package main
import "net"
import "fmt"
func main() {
  ServerConn, _ := net.ListenUDP("udp", &net.UDPAddr{IP:[]byte{0,0,0,0},Port:10001,Zone:""})
  defer ServerConn.Close()
  buf := make([]byte, 1024)
  for {
    n, addr, _ := ServerConn.ReadFromUDP(buf)
    fmt.Println("Received ", string(buf[0:n]), " from ", addr)
  }
}

Now a client. It sends packets to localhost UDP port 10001, each saying “hello”:

package main
import "net"
func main() {
  Conn, _ := net.DialUDP("udp", nil, &net.UDPAddr{IP:[]byte{127,0,0,1},Port:10001,Zone:""})
  defer Conn.Close()
  Conn.Write([]byte("hello"))
}

By running the server, then running our client repeatedly, we get:

% go run server.go
Received  hello  from  127.0.0.1:55877
Received  hello  from  127.0.0.1:61029
Received  hello  from  127.0.0.1:52922
Tagged #golang, #udp, #networking.

Similar posts

More by Jim

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

This page copyright James Fisher 2016. Content is not associated with my employer. Found an error? Edit this page.