UDP datagrams
Build a UDP server
Bind a loopback UDP socket, receive datagrams, and inspect sender address and port.
10 minute lesson
TCP gave you a connected byte stream. UDP gives you the opposite: independent messages called datagrams, delivered without a connection handshake. Each datagram arrives whole or not at all — no stream, no ordering guarantee, no automatic retransmission.
UDP delivers independent datagrams, and each message event includes exactly one datagram plus the remote endpoint that sent it.
Node exposes UDP through node:dgram. Create udp-server.mjs:
import dgram from 'node:dgram'
const socket = dgram.createSocket('udp4')
socket.on('message', (message, remote) => {
console.log(message.toString(), remote)
})
socket.bind(41234, '127.0.0.1')
Notice what’s missing compared to TCP: no createServer, no per-connection callback, no accepted socket. One socket receives datagrams from every sender. The remote object is how you tell senders apart — and where you’d send a reply.
bind(41234, '127.0.0.1') claims UDP port 41234 on loopback. UDP and TCP ports are separate namespaces, so a TCP listener on 41234 wouldn’t conflict.
Verify it
Confirm the UDP listener:
ss -lnu | grep 41234
# UNCONN 0 0 127.0.0.1:41234 0.0.0.0:*
The state says UNCONN instead of LISTEN — UDP sockets don’t listen for connections, they just receive whatever arrives.
Send a datagram with netcat in UDP mode:
echo hello | nc -u 127.0.0.1 41234
The server prints:
hello { address: '127.0.0.1', family: 'IPv4', port: 58239, size: 6 }
One send should produce one message event. That’s the property UDP gives you that TCP doesn’t: message boundaries are preserved. Six bytes sent (five letters plus the newline) arrive as one six-byte datagram — never split across events, never merged with the next one. No framing code needed.
The port in the remote info is the sender’s ephemeral port, picked by its OS. Run the nc command twice and you’ll see a different number each time.
One caution before you build on this. UDP source addresses can be spoofed in some networks — nothing in the protocol proves a datagram came from the address it claims. Do not treat a received datagram as authenticated identity; anything that changes state needs validation of its own.
Lesson completed