March Docs

Udp

UDP datagram sockets, built for packet rate.

Every send and receive moves a BATCH of datagrams per kernel crossing: on Linux recvmmsg/sendmmsg plus UDP GSO (up to 64 equal-sized datagrams per transit) and opt-in GRO; elsewhere a nonblocking drain loop. Waits park the green thread, never an OS thread, so one scheduler thread can serve many sockets. For more than one core's worth of packets, open open_sharded sockets (SO_REUSEPORT) and give each its own task.

"Reliable" here means the socket layer never loses data on its own: sends wait for buffer space instead of dropping, and stats reports the datagrams the KERNEL dropped for lack of receive-buffer room, so a receiver that falls behind knows it. UDP itself still delivers each datagram at most once, in any order, or not at all.

Packets are binary-safe Strings. An UdpAddr is an opaque, comparable address value: get one from resolve, local_addr or a received datagram.

Public API: Udp.open(host, port) : Result(UdpSocket, UdpError) Udp.open_with(host, port, opts) : Result(UdpSocket, UdpError) Udp.open_sharded(host, port, n, opts) : Result(List(UdpSocket), UdpError) Udp.defaults() : UdpOptions Udp.resolve(host, port) : Result(UdpAddr, UdpError) Udp.connect(sock, addr) : Result((), UdpError) Udp.send_to(sock, addr, data) : Result((), UdpError) Udp.send(sock, data) : Result((), UdpError) Udp.send_batch(sock, addr, payloads) : Result(Int, UdpError) Udp.send_batch_connected(sock, payloads) : Result(Int, UdpError) Udp.send_many(sock, [(addr, data)]) : Result(Int, UdpError) Udp.recv(sock, max_size, timeout_ms) : Result(Option((UdpAddr, String)), UdpError) Udp.recv_batch(sock, max_msgs, max_size, ms) : Result(List((UdpAddr, String)), UdpError) Udp.local_addr(sock) / Udp.local_port(sock) Udp.addr_to_string(addr) / Udp.addr_port(addr) Udp.stats(sock) : UdpStats Udp.close(sock) : () Udp.error_message(e) : String

Types

typeUdpErrorUdpError#
typeUdpSocketUdpSocket = UdpSocket(Int)#

An open UDP socket. Close it with Udp.close.

typeUdpAddrUdpAddr = UdpAddr(String)#

An opaque IPv4 or IPv6 address and port; compare with ==.

typeUdpOptionsUdpOptions = {#

UdpSocket options for open_with.

  • reuse_addr, reuse_port: SO_REUSEADDR / SO_REUSEPORT. reuse_port
lets several sockets bind one port; Linux spreads flows across them.
  • broadcast: allow sending to a broadcast address.
  • gso: batch equal-sized sends into one kernel transit (Linux; turned
off automatically if the kernel or NIC refuses it).
  • gro: let the kernel coalesce a flow's received datagrams (Linux).
Datagrams still come back one by one; fewer syscalls deliver them.
  • recv_buffer, send_buffer: requested socket buffer bytes (0 keeps
the OS default). Linux caps them at net.core.rmem_max / wmem_max unless
the process has CAP_NET_ADMIN; raise those sysctls for real receive
headroom, since a full receive buffer is where UDP loses packets.
typeUdpStatsUdpStats = { rx_dropped: Int, tx_stalls: Int }#

Counters for a socket. rx_dropped is the kernel's count of datagrams dropped because the receive buffer was full, as of the last receive (Linux; -1 where the platform does not report it). tx_stalls counts the times a send had to wait for buffer space instead of dropping.

Functions

fnaddr_portaddr_port(a : UdpAddr) : {Int | _ >= 0 && _ <= 65535}#

The port of an address.

fnaddr_to_stringaddr_to_string(a : UdpAddr) : String#

Render an address: "127.0.0.1:9000", "[::1]:9000".

fncloseclose(sock : UdpSocket) : ()#

Close the socket.

fnconnectconnect(sock : UdpSocket, a : UdpAddr) : Result((), UdpError)#

Fix the socket's peer. send and send_batch_connected then need no address, the kernel skips a route lookup per datagram, only that peer's datagrams are received, and an ICMP "port unreachable" surfaces as an error on a later call instead of vanishing.

fndefaultsdefaults() : UdpOptions#

The defaults open uses: GSO on, GRO off, 8 MiB receive and send buffers requested, no address reuse.

Examples

Udp.open_with("0.0.0.0", 9000, { Udp.defaults() with reuse_port: true })
fnerror_messageerror_message(e : UdpError) : String#

A human-readable description of a UdpError.

Examples

Udp.error_message(SendFailed("boom"))  -- "send failed: boom"
fnlocal_addrlocal_addr(sock : UdpSocket) : Result(UdpAddr, UdpError)#

The address this socket is bound to.

fnlocal_portlocal_port(sock : UdpSocket) : Result({Int | _ >= 0 && _ <= 65535}, UdpError)#

The port this socket is bound to (the one the OS picked for port 0).

fnopenopen(host : String, port : {Int | _ >= 0 else "a port is at least 0" && _ <= 65535 else "a port is at most 65535"}) : Result(UdpSocket, UdpError)#

Bind a UDP socket with defaults(). host "" or "0.0.0.0" is every IPv4 interface, "::" every interface over IPv4 and IPv6; port 0 picks a free port (see local_port).

Examples

let? sock = Udp.open("127.0.0.1", 0)
fnopen_shardedopen_sharded(host : String, port : {Int | _ >= 0 else "a port is at least 0" && _ <= 65535 else "a port is at most 65535"}, n : {Int | _ > 0 else "open at least one shard"},#

Open n sockets on one port with SO_REUSEPORT, one per receiving task. Linux hashes each flow to one socket, so n tasks each draining their own socket scale across cores. Port 0 picks a free port for the first and binds the rest to it. On failure every socket opened so far is closed.

Examples

let? socks = Udp.open_sharded("0.0.0.0", 9000, 4, Udp.defaults())
fnopen_withopen_with(host : String, port : {Int | _ >= 0 else "a port is at least 0" && _ <= 65535 else "a port is at most 65535"}, opts : UdpOptions) : Result(UdpSocket, UdpError)#

Bind a UDP socket with explicit options.

Examples

Udp.open_with("::", 5353, { Udp.defaults() with reuse_addr: true })
fnrecvrecv(sock : UdpSocket, max_size : {Int | _ > 0 else "max_size must be positive" && _ <= 65535 else "a datagram is at most 65535 bytes"}, timeout_ms : Int) : Result(Option((UdpAddr, String)), UdpError)#

Receive one datagram; Ok(None) if none arrives within timeout_ms. Prefer recv_batch for volume.

fnrecv_batchrecv_batch(sock : UdpSocket, max_msgs : {Int | _ > 0 else "receive at least one datagram" && _ <= 1024 else "at most 1024 datagrams per batch"},#

Receive up to max_msgs datagrams, in arrival order, each as (from, payload). Whatever is already queued comes back at once; otherwise the task parks until data arrives or timeout_ms passes (0: do not wait; negative: wait for ever). A timeout is Ok([]). A payload longer than max_size is truncated to it; 65535 never truncates.

Examples

match Udp.recv_batch(sock, 256, 2048, 100) do
  Ok(dgrams) -> List.map(dgrams, handle)
  Err(e)     -> println(Udp.error_message(e))
end
fnresolveresolve(host : String, port : {Int | _ >= 0 else "a port is at least 0" && _ <= 65535 else "a port is at most 65535"}) : Result(UdpAddr, UdpError)#

Look up host and pair it with port. IPv4 is preferred when the host has both, so the address works from an IPv4 socket. Resolve once and reuse the UdpAddr: sends take it without another lookup.

Examples

let? dst = Udp.resolve("127.0.0.1", 9000)
fnsendsend(sock : UdpSocket, data : String) : Result((), UdpError)#

Send one datagram to the connected peer.

fnsend_batchsend_batch(sock : UdpSocket, a : UdpAddr, payloads : List(String)) : Result({Int | _ == len(payloads)}, UdpError)#

Send every payload to a, in order, as one batch: the fast path. Waits for buffer space rather than dropping. Ok(n) once all n are sent; a hard failure (e.g. a payload over 65507 bytes) is Err(SendFailed(msg)) naming how many went out first.

Examples

let? n = Udp.send_batch(sock, dst, List.map(seqs, encode))
fnsend_batch_connectedsend_batch_connected(sock : UdpSocket, payloads : List(String)) : Result({Int | _ == len(payloads)}, UdpError)#

send_batch to the connected peer (see connect).

fnsend_manysend_many(sock : UdpSocket, pairs : List((UdpAddr, String))) : Result({Int | _ == len(pairs)}, UdpError)#

Send a batch with a destination per datagram. Consecutive datagrams to one destination still share a kernel transit.

fnsend_tosend_to(sock : UdpSocket, a : UdpAddr, data : String) : Result((), UdpError)#

Send one datagram to a. Prefer send_batch for volume.

fnstatsstats(sock : UdpSocket) : UdpStats#

The socket's drop and backpressure counters (see UdpStats).