48 / Networking

UDP Socket

UDP is a connectionless protocol: each datagram is independent, with no handshake or guaranteed delivery. udp_bind creates a socket, udp_sendto sends data to an address, and udp_recvfrom receives data. UDP is ideal for real-time applications where low latency matters more than reliability.

48-udp-socket.nxSource →
// UDP send and receive — connectionless datagrams
// Envío y recepción UDP — datagramas sin conexión

fn main() -> int {
    // Bind a UDP socket to a local port
    let sock: int = udp_bind("127.0.0.1", 9001)
    if sock < 0 {
        print("failed to bind UDP socket")
        return 1
    }
    print("UDP socket bound to :9001")

    // Send a datagram to a remote address
    let msg: String = "hello via UDP"
    udp_sendto(sock, msg, "127.0.0.1", 9001)
    print("sent: " + msg)

    // Receive a datagram (blocks until one arrives)
    let received: String = udp_recvfrom(sock, 1024)
    print("received: " + received)

    tcp_close(sock)
    return 0
}
Outputstdout
UDP socket bound to :9001
sent: hello via UDP
received: hello via UDP

How it works

udp_bind(host, port) creates a UDP socket bound to the given address. Unlike TCP, there is no connection setup — you can immediately send to any address with udp_sendto(sock, data, host, port). udp_recvfrom(sock, max_bytes) blocks until a datagram arrives.

In this example, the socket sends to itself (loopback). In practice, you would have separate sender and receiver sockets on different hosts or ports. UDP sockets are closed with tcp_close (same underlying file descriptor mechanism).