node:dgram module provides an implementation of UDP datagram sockets.
Import
Class: dgram.Socket
Encapsulates the datagram functionality for UDP communication.Creating a UDP Socket
Events
Event: ‘close’
Emitted after a socket is closed withclose().
Event: ‘connect’
Emitted after a socket is associated to a remote address as a result of a successfulconnect() call.
Event: ‘error’
exception
Event: ‘listening’
Emitted once the socket is addressable and can receive data.Event: ‘message’
msgThe messagerinfoRemote address informationaddressSender addressfamilyAddress family (‘IPv4’ or ‘IPv6’)portSender portsizeMessage size
Methods
socket.bind([port][, address][, callback])
portaddresscallback
socket.bind(options[, callback])
optionsportaddressexclusive
callback
socket.send(msg[, offset, length][, port][, address][, callback])
msgoffsetlengthportaddresscallback
Sending Multiple Buffers
socket.connect(port[, address][, callback])
portaddresscallback
socket.disconnect()
Disassociates a connected socket from its remote address.socket.close([callback])
callback
socket.address()
- Returns:
socket.setBroadcast(flag)
flag
SO_BROADCAST socket option.
socket.setTTL(ttl)
ttl1-255
IP_TTL socket option.
socket.setMulticastTTL(ttl)
ttl0-255
IP_MULTICAST_TTL socket option.
socket.setMulticastLoopback(flag)
flag
IP_MULTICAST_LOOP socket option.
socket.addMembership(multicastAddress[, multicastInterface])
multicastAddressmulticastInterface
socket.dropMembership(multicastAddress[, multicastInterface])
multicastAddressmulticastInterface
Factory Functions
dgram.createSocket(type[, callback])
type‘udp4’ or ‘udp6’callbackAttached as a listener for ‘message’ events- Returns:
dgram.createSocket(options[, callback])
optionstype‘udp4’ or ‘udp6’ (required)reuseAddrDefault: falseipv6OnlyDefault: falserecvBufferSizeSO_RCVBUFvaluesendBufferSizeSO_SNDBUFvaluelookupCustom lookup function
callback
Examples
Echo Server
UDP Client
Multicast Receiver
Multicast Sender
Broadcast Example
Connected Socket Example
Datagram Size Limits
The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit):- IPv4: Maximum payload is typically 65,507 bytes (65,535 - 8 bytes UDP header - 20 bytes IP header)
- IPv6: Minimum MTU is 1280 octets
- Practical limit: Usually 1500 bytes (Ethernet MTU)
Safe Datagram Size
Error Handling
Best Practices
- Always handle errors - UDP is unreliable
- Keep messages small - Avoid fragmentation
- Use connected sockets - For peer-to-peer communication
- Implement timeouts - UDP doesn’t guarantee delivery
- Consider message ordering - Messages may arrive out of order
- Add checksums - For data integrity
- Implement retry logic - For critical messages