Java UDP Sockets: DatagramSocket and DatagramPacket

UDP sends independent datagrams with no connection, no delivery guarantee and no ordering. In return it is simple and fast, with no handshake and no retransmission delays, which suits metrics, game state, DNS and media where a late packet is worth less than a lost one.

Share

Contents

How UDP works

UDP (User Datagram Protocol) is the thin layer over IP that TCP is not. A program hands the operating system a datagram, a block of bytes with a destination address and port, and the system sends it as one IP packet, or a few fragments. There is no handshake, no acknowledgment, no retransmission and no ordering: a datagram arrives once, intact, or not at all, and sometimes more than once or out of order. What UDP does keep is the message boundary, and it adds almost no delay, which is why DNS, voice, video, games and QUIC (the transport under HTTP/3) are built on it.

Each UDP socket has a receive buffer in the kernel. Datagrams that arrive while it is full are simply dropped, and so are datagrams for a port where nothing listens; the only trace may be an ICMP "port unreachable" message back to the sender.

UDP APIs in the JDK
ClassSinceBest for
DatagramSocket, DatagramPacketJava 1.0Simple blocking senders and receivers
MulticastSocketJava 1.1Joining multicast groups on a local network
DatagramChannelJava 1.4 (NIO)Non-blocking UDP, selectors, ByteBuffers
Reimplemented DatagramSocket on NIOJava 15 (JEP 373)Same API, simpler implementation

All programs run on the loopback interface on JDK 21 under Linux.

Sending and receiving datagrams

A DatagramSocket sends and receives DatagramPackets. There is no accept and no connection: each outgoing packet names its destination, and each incoming packet records its sender. The program sends three sensor readings, replies to each one, and then tests two edge cases.

Java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;

public class UdpBasics {

    public static void main(String[] args) throws Exception {
        InetAddress lo = InetAddress.getLoopbackAddress();
        try (DatagramSocket server = new DatagramSocket(0, lo);
             DatagramSocket client = new DatagramSocket(0, lo)) {

            // No connection: every packet carries its destination
            for (String m : new String[] {"temp=21.5", "temp=21.7", "temp=21.6"}) {
                byte[] data = m.getBytes(StandardCharsets.UTF_8);
                client.send(new DatagramPacket(data, data.length, lo, server.getLocalPort()));
            }

            // Each receive() returns exactly one datagram: message boundaries are kept
            byte[] buf = new byte[1500];
            for (int i = 0; i < 3; i++) {
                DatagramPacket p = new DatagramPacket(buf, buf.length);
                server.receive(p);
                String text = new String(p.getData(), 0, p.getLength(), StandardCharsets.UTF_8);
                System.out.println("received \"" + text + "\" (" + p.getLength()
                        + " bytes) from the client's port: "
                        + (p.getPort() == client.getLocalPort()));

                // Reply to whoever sent it
                byte[] ack = ("ack " + text).getBytes(StandardCharsets.UTF_8);
                server.send(new DatagramPacket(ack, ack.length, p.getSocketAddress()));
            }
            DatagramPacket reply = new DatagramPacket(new byte[100], 100);
            client.receive(reply);
            System.out.println("client got: "
                    + new String(reply.getData(), 0, reply.getLength(), StandardCharsets.UTF_8));

            // A datagram larger than the buffer is cut off, the rest is lost
            byte[] big = "0123456789".repeat(10).getBytes(StandardCharsets.UTF_8);
            client.send(new DatagramPacket(big, big.length, lo, server.getLocalPort()));
            DatagramPacket small = new DatagramPacket(new byte[16], 16);
            server.receive(small);
            System.out.println("sent 100 bytes into a 16-byte buffer, received "
                    + small.getLength());

            // Nothing guarantees an answer: always use a timeout
            client.setSoTimeout(300);
            try {
                // two acks are still queued, the third receive finds nothing
                client.receive(new DatagramPacket(new byte[100], 100));
                client.receive(new DatagramPacket(new byte[100], 100));
                client.receive(new DatagramPacket(new byte[100], 100));
            } catch (SocketTimeoutException e) {
                System.out.println("no more datagrams: SocketTimeoutException after 300 ms");
            }
        }
    }
}

Output:

Output
received "temp=21.5" (9 bytes) from the client's port: true
received "temp=21.7" (9 bytes) from the client's port: true
received "temp=21.6" (9 bytes) from the client's port: true
client got: ack temp=21.5
sent 100 bytes into a 16-byte buffer, received 16
no more datagrams: SocketTimeoutException after 300 ms
  • Unlike TCP (see TCP sockets, where three writes arrived as one read), each receive returned exactly one datagram. UDP keeps message boundaries, so no framing is needed.
  • p.getSocketAddress() is the sender's address and port; sending the reply there is how request/response works without connections.
  • Use p.getLength(), not the buffer length, when reading the data: the buffer is reused and may hold old bytes beyond the current datagram.
  • A 100-byte datagram received into a 16-byte buffer was cut to 16 bytes, and the rest is gone. Size the buffer for the largest datagram you expect. Keep datagrams under about 1,400 bytes on the internet so they are not fragmented, which raises the chance of losing them.
  • receive blocks forever by default. With setSoTimeout, it throws SocketTimeoutException when nothing arrives, which is how UDP clients detect a lost request.

Loss happens silently

UDP gives no feedback when a datagram is dropped. To show it without a real network, the program gives the receiver a small 16 KB socket buffer and sends 2,000 numbered 1,000-byte datagrams as fast as possible before reading any of them.

Java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;

public class UdpLoss {

    public static void main(String[] args) throws Exception {
        InetAddress lo = InetAddress.getLoopbackAddress();
        try (DatagramSocket receiver = new DatagramSocket(0, lo);
             DatagramSocket sender = new DatagramSocket(0, lo)) {
            receiver.setReceiveBufferSize(16 * 1024);            // a deliberately small buffer
            receiver.setSoTimeout(500);

            // Send 2,000 numbered datagrams as fast as possible while nobody reads
            int sent = 2000;
            byte[] payload = new byte[1000];
            for (int i = 0; i < sent; i++) {
                ByteBuffer.wrap(payload).putInt(i);
                sender.send(new DatagramPacket(payload, payload.length, lo,
                        receiver.getLocalPort()));
            }

            int received = 0;
            int lastSeq = -1;
            boolean inOrder = true;
            byte[] buf = new byte[1500];
            try {
                while (true) {
                    DatagramPacket p = new DatagramPacket(buf, buf.length);
                    receiver.receive(p);
                    int seq = ByteBuffer.wrap(p.getData()).getInt();
                    inOrder &= seq > lastSeq;
                    lastSeq = seq;
                    received++;
                }
            } catch (SocketTimeoutException done) {
                // no more datagrams
            }
            System.out.println("sent " + sent + ", received " + received + ", lost "
                    + (sent - received) + " without any error on either side");
            System.out.println("lost some: " + (received < sent) + ", arrivals in order: "
                    + inOrder);
        }
    }
}

Output (the exact count depends on the operating system's buffer handling):

Output
sent 2000, received 14, lost 1986 without any error on either side
lost some: true, arrivals in order: true

Nearly all datagrams were dropped because the receive buffer filled up, and neither send nor receive reported a problem. Over a real network, routers drop packets the same way under load, and packets can also arrive out of order or duplicated. Here, on one machine, the survivors arrived in order, but that is not guaranteed.

Applications built on UDP therefore add what they need themselves: sequence numbers to detect loss and reordering, acknowledgements and retries for important messages, and rate limits. If you find yourself adding all of these, TCP, or QUIC (which HTTP/3 uses), is usually the better choice.

Connected sockets, size limits and channels

Three details change how UDP code behaves: whether the socket is connected, how large a datagram may be, and whether reads block. The program sends to a port where nothing listens twice, once unconnected and once connected, tries the largest possible datagram and one byte more, and uses a non-blocking DatagramChannel.

Java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.PortUnreachableException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class ConnectedAndLimits {

    public static void main(String[] args) throws Exception {
        InetAddress lo = InetAddress.getLoopbackAddress();

        // 1. A connected socket learns about "port unreachable" from the OS
        int freePort;
        try (DatagramSocket probe = new DatagramSocket(0, lo)) {
            freePort = probe.getLocalPort();                  // closed again: nobody listens
        }
        try (DatagramSocket s = new DatagramSocket()) {
            s.setSoTimeout(500);
            s.send(new DatagramPacket(new byte[1], 1, lo, freePort));
            try {
                s.receive(new DatagramPacket(new byte[10], 10));
            } catch (SocketTimeoutException e) {
                System.out.println("unconnected socket, nobody listening: timeout after 500 ms");
            }
        }
        try (DatagramSocket s = new DatagramSocket()) {
            s.setSoTimeout(500);
            s.connect(lo, freePort);
            s.send(new DatagramPacket(new byte[1], 1));
            try {
                s.receive(new DatagramPacket(new byte[10], 10));
            } catch (PortUnreachableException e) {
                System.out.println("connected socket, nobody listening: PortUnreachableException");
            }
        }

        // 2. Size limits: a UDP payload over IPv4 is at most 65,507 bytes
        try (DatagramSocket s = new DatagramSocket()) {
            for (int size : new int[] {65507, 65508}) {
                try {
                    s.send(new DatagramPacket(new byte[size], size, lo, freePort));
                    System.out.println(size + "-byte datagram: sent");
                } catch (java.io.IOException e) {
                    System.out.println(size + "-byte datagram: " + e.getMessage());
                }
            }
            System.out.println("default buffers: receive " + s.getReceiveBufferSize()
                    + " bytes, send " + s.getSendBufferSize() + " bytes");
        }

        // 3. DatagramChannel in non-blocking mode: receive returns null when empty
        try (DatagramChannel ch = DatagramChannel.open()) {
            ch.bind(new InetSocketAddress(lo, 0));
            ch.configureBlocking(false);
            ByteBuffer buf = ByteBuffer.allocate(100);
            System.out.println("non-blocking receive with nothing queued: " + ch.receive(buf));
            ch.send(ByteBuffer.wrap("ping".getBytes()), ch.getLocalAddress());
            Thread.sleep(50);
            System.out.println("after sending to itself: received " + (ch.receive(buf) != null)
                    + ", " + buf.flip().remaining() + " bytes");
        }
    }
}

Output:

Output
unconnected socket, nobody listening: timeout after 500 ms
connected socket, nobody listening: PortUnreachableException
65507-byte datagram: sent
65508-byte datagram: Message too long
default buffers: receive 106496 bytes, send 106496 bytes
non-blocking receive with nothing queued: null
after sending to itself: received true, 4 bytes
  • The unconnected socket learned nothing: its receive simply timed out after 500 ms. After connect, the same situation threw PortUnreachableException, because the operating system delivers the ICMP error to a connected socket. A connected UDP socket also accepts datagrams only from that one peer, which filters out stray traffic. No packets are exchanged by connect itself.
  • A UDP payload over IPv4 can be at most 65,507 bytes (65,535 minus the IP and UDP headers). One byte more failed with "Message too long". Large datagrams are fragmented by IP, and losing any fragment loses the whole datagram, so real protocols stay near 1,200 to 1,400 bytes.
  • The default kernel buffers here were about 104 KB each way. A burst bigger than the receive buffer is lost, as the previous program showed; setReceiveBufferSize asks for more, within the operating system's limits.
  • In non-blocking mode, DatagramChannel.receive returned null when nothing was queued instead of waiting, which lets one thread serve many channels with a selector.

Adding reliability: timeouts, retries and sequence numbers

When a request must get an answer, the client has to detect loss and retry, and it must not confuse a late reply with a new one. The server below "loses" every second request it receives. The client numbers each request, waits 200 ms for a reply with the same number, and retries up to three times.

Java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;

public class RetryClient {

    public static void main(String[] args) throws Exception {
        InetAddress lo = InetAddress.getLoopbackAddress();
        try (DatagramSocket server = new DatagramSocket(0, lo);
             DatagramSocket client = new DatagramSocket(0, lo)) {
            // A flaky server: ignores every second request it receives
            Thread.ofVirtual().start(() -> {
                byte[] buf = new byte[8];
                int seen = 0;
                while (!server.isClosed()) {
                    try {
                        DatagramPacket p = new DatagramPacket(buf, buf.length);
                        server.receive(p);
                        if (seen++ % 2 == 1) {
                            continue;                            // "lost"
                        }
                        long seq = ByteBuffer.wrap(buf, 0, 8).getLong();
                        byte[] reply = ByteBuffer.allocate(8).putLong(seq).array();
                        server.send(new DatagramPacket(reply, 8, p.getSocketAddress()));
                    } catch (Exception e) {
                        return;
                    }
                }
            });

            client.setSoTimeout(200);
            int totalTries = 0;
            for (long seq = 1; seq <= 4; seq++) {
                byte[] req = ByteBuffer.allocate(8).putLong(seq).array();
                for (int attempt = 1; attempt <= 3; attempt++) {
                    totalTries++;
                    client.send(new DatagramPacket(req, 8, lo, server.getLocalPort()));
                    try {
                        DatagramPacket reply = new DatagramPacket(new byte[8], 8);
                        client.receive(reply);
                        long ack = ByteBuffer.wrap(reply.getData()).getLong();
                        if (ack != seq) {
                            System.out.println("  stale reply for " + ack + ", ignored");
                            attempt--;
                            continue;
                        }
                        System.out.println("request " + seq + ": answered on attempt " + attempt);
                        break;
                    } catch (SocketTimeoutException e) {
                        System.out.println("request " + seq + ": no reply within 200 ms");
                    }
                }
            }
            System.out.println("4 requests needed " + totalTries + " datagrams");
        }
    }
}

Output:

Output
request 1: answered on attempt 1
request 2: no reply within 200 ms
request 2: answered on attempt 2
request 3: no reply within 200 ms
request 3: answered on attempt 2
request 4: no reply within 200 ms
request 4: answered on attempt 2
4 requests needed 7 datagrams
  • Request 1 was answered at once. From then on, the server ignored every second datagram, so requests 2 to 4 each timed out once and succeeded on the second attempt: 7 datagrams for 4 requests.
  • The sequence number is what makes retries safe. If a reply arrives after the client has already retried, the client recognizes the old number and ignores it, instead of taking it as the answer to the next request.
  • A retried request may reach the server twice, so the server must treat repeated requests as harmless (idempotent), or remember recent sequence numbers. DNS resolvers work exactly this way: a short timeout, a few retries, and an id in every query.
  • Real clients also back off, waiting longer after each timeout, so that a struggling server is not flooded with retries.

Is UDP faster than TCP?

UDP is often chosen "for speed", so it is worth measuring what that means. The program sends 10,000 small 32-byte request-reply pairs over UDP, and over an already open TCP connection with TCP_NODELAY, after a warm-up round, and shows the best of 3 rounds. This is a rough loopback measurement on a 2-CPU Linux machine with JDK 21.

Java
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class PingLatency {

    static final int N = 10000;

    public static void main(String[] args) throws Exception {
        InetAddress lo = InetAddress.getLoopbackAddress();

        // UDP echo
        try (DatagramSocket server = new DatagramSocket(0, lo);
             DatagramSocket client = new DatagramSocket()) {
            Thread.ofPlatform().daemon().start(() -> {
                DatagramPacket p = new DatagramPacket(new byte[64], 64);
                try {
                    while (true) {
                        server.receive(p);
                        server.send(new DatagramPacket(p.getData(), p.getLength(),
                                p.getSocketAddress()));
                    }
                } catch (Exception e) {
                    // socket closed
                }
            });
            client.connect(lo, server.getLocalPort());
            DatagramPacket out = new DatagramPacket(new byte[32], 32);
            DatagramPacket in = new DatagramPacket(new byte[64], 64);
            long best = Long.MAX_VALUE;
            for (int round = 0; round < 4; round++) {             // round 0 is a warm-up
                long t0 = System.nanoTime();
                for (int i = 0; i < N; i++) {
                    client.send(out);
                    client.receive(in);
                }
                if (round > 0) {
                    best = Math.min(best, System.nanoTime() - t0);
                }
            }
            System.out.printf("UDP round trip, 32 bytes:                  %5.1f us%n",
                    best / (double) N / 1000);
        }

        // TCP echo over one existing connection
        try (ServerSocket server = new ServerSocket(0, 50, lo)) {
            Thread.ofPlatform().daemon().start(() -> {
                try (Socket s = server.accept()) {
                    s.setTcpNoDelay(true);
                    InputStream in = s.getInputStream();
                    OutputStream out = s.getOutputStream();
                    byte[] buf = new byte[32];
                    while (in.readNBytes(buf, 0, 32) == 32) {
                        out.write(buf);
                    }
                } catch (Exception e) {
                    // connection closed
                }
            });
            try (Socket c = new Socket(lo, server.getLocalPort())) {
                c.setTcpNoDelay(true);
                OutputStream out = c.getOutputStream();
                InputStream in = c.getInputStream();
                byte[] buf = new byte[32];
                long best = Long.MAX_VALUE;
                for (int round = 0; round < 4; round++) {
                    long t0 = System.nanoTime();
                    for (int i = 0; i < N; i++) {
                        out.write(buf);
                        in.readNBytes(buf, 0, 32);
                    }
                    if (round > 0) {
                        best = Math.min(best, System.nanoTime() - t0);
                    }
                }
                System.out.printf("TCP round trip, 32 bytes, open connection: %5.1f us%n",
                        best / (double) N / 1000);
            }
        }
    }
}

Output of the round-trip run:

Output
UDP round trip, 32 bytes:                    3.8 us
TCP round trip, 32 bytes, open connection:   6.1 us
  • Both round trips took a few microseconds. UDP was somewhat faster, but once a TCP connection exists, sending small messages over it costs the same order of magnitude; the work is dominated by system calls and thread wake-ups, not by the protocol.
  • UDP's real advantages lie elsewhere: there is no connection to set up, which saves a full round trip before the first byte (a lot across continents), and a lost packet does not hold up the ones behind it. TCP must deliver bytes in order, so one lost segment stalls everything after it until it is retransmitted, which hurts live audio and video.
  • Without those needs, TCP's reliability is worth far more than the microseconds, and protocols like QUIC show how much work it takes to rebuild that reliability on top of UDP.

TCP or UDP?

Comparing the two protocols
TCPUDP
ConnectionYes, with a handshakeNo
Delivery and orderGuaranteed, with retransmissionNot guaranteed
Message boundariesNot kept; a byte streamKept; one datagram per receive
Typical usesHTTP/1.1 and HTTP/2, databases, file transferDNS, metrics (StatsD), games, voice and video
Java classesSocket, ServerSocketDatagramSocket, DatagramChannel, MulticastSocket

A practical rule: choose UDP when a late message is worthless (a position update in a game, a frame of live audio), when each exchange is one small request and one small reply (DNS, NTP, metrics), or when you implement a protocol that defines its own reliability, such as QUIC. Choose TCP, or a library on top of it, for everything else. In both cases, set timeouts on every blocking call, size buffers for bursts, and never trust the sender address of a datagram for authentication: UDP source addresses are easy to forge, which is also what makes UDP services usable for amplification attacks when a small request triggers a large reply.

UDP also supports multicast, sending one datagram to every member of a group on the local network, through MulticastSocket or a DatagramChannel joined to a group.