udp is a module — import udp — and it is a separate module from tcp
on purpose. A datagram is a message and a stream is not: it arrives whole or
not at all, it may arrive twice, and it may not arrive. There is no
write_all, no half-close, no “the peer closed”, a zero-length datagram is an
ordinary thing to send, and a receive answers two facts where every tcp
operation answers one.
An exchange
import net
import udp
fn ask(server net.SocketAddr, question []byte) int ! udp.Error {
sock := udp.bind("127.0.0.1:0")?
sock.send_to(question, server)?
mut buf: []byte = List.new[byte](1500)
d := sock.receive_from(&mut buf, 1500)?
println("${d.bytes} bytes from ${d.from}")
return d.bytes
}
fn main() void {
server := net.SocketAddr { ip: net.IpAddr.loopback_v4(), port: 9999 }
match ask(server, [1u8, 2u8, 3u8]) {
Ok(n) => println("${n} back")
Err(e) => println("no answer")
}
}bind takes host:port; :0 lets the kernel pick a port, and port()
answers what it picked, as a u16.
send_to takes the address the datagram goes to as a
net.SocketAddr, which needs nothing looked
up: net.SocketAddr.parse reads one from text, and receive_from answers
one. A destination that is a name is send_to_host(buf, "host:port"), which
resolves it to the one address of the family the socket is.
Who sent it comes back with the bytes
receive_from answers a udp.Datagram — bytes, from and truncated — in
one call, and that is a deliberate cost. The cheaper shape is a “last sender” slot
on the socket read by a second call, and it is a data race by construction: a
socket with two receiving tasks is ordinary, and the second receive overwrites
the slot the first is about to read.
from is a net.SocketAddr: the sender’s
address and port, which the host writes into the answer as words, so nothing is
allocated for it however many datagrams a loop receives. A reply to a sender
is sock.send_to(buf, d.from): the address goes back as the words it came in,
scope included, with no text between.
A v4 sender reaching a dual-stack socket answers 1.2.3.4, not
::ffff:1.2.3.4, so an allow-list written on one machine means the same thing
on another. A link-local v6 sender keeps the interface it is on, fe80::1%3,
because a datagram can only be answered on the link it arrived on and sending
to a link-local address with no scope fails.
Truncation loses the tail, silently
A datagram larger than the buffer you offered is truncated and the rest is discarded. That is the kernel’s behaviour and nothing on this side can undo it — the bytes are gone by the time the call returns, and no call fails. It is the one place a program loses data without being told.
The remedy is only ever a big enough buffer. udp.MAX_PAYLOAD is 65507, the
largest a UDP payload can be; most protocols stay under 1200 because a
fragmented datagram loses everything if one fragment is lost.
Connecting a datagram socket
connect(addr) fixes the peer. A connected socket takes send and receive
with no address, drops datagrams from anywhere else, and — the part worth
connecting for — receives ICMP errors. An unconnected socket has nothing to
attribute a port-unreachable to, so it is the only way a UDP program learns
that nothing is listening at the other end.
import udp
fn probe(addr string) bool {
sock := match udp.bind("127.0.0.1:0") { Ok(s) => s Err(e) => return false }
match sock.connect(addr) { Ok(k) => {} Err(e) => return false }
match sock.send([0u8]) { Ok(k) => {} Err(e) => return false }
mut buf: []byte = List.new[byte](64)
return match sock.receive(&mut buf, 64) {
Ok(n) => true
Err(ConnectionRefused { addr }) => false
Err(e) => false
}
}
fn main() void {
if probe("127.0.0.1:9999") {
println("something answered")
} else {
println("nothing there")
}
}Options
| Method | What it does |
|---|---|
hops(ttl) |
the IP time-to-live on unicast datagrams |
recv_buffer(bytes) / send_buffer(bytes) |
the kernel’s buffers |
broadcast(on) |
allow sending to a broadcast address |
multicast_loop(on) |
whether this host receives its own multicast sends |
multicast_hops(ttl) |
how many routers a multicast datagram crosses |
broadcast is off and asked for by name: the kernel refuses a send to a
broadcast address without it, which is a loud failure, and turning it on
unasked would turn a typo in an address into a packet every host on the segment
receives.
multicast_loop is on in the kernel, which surprises everyone who writes a
discovery protocol and sees its own announcements come back.
Multicast
join(group, iface) and leave(group, iface) name the interface, and that
is the argument worth reading twice. A host with several interfaces joins a
group on one of them, and the kernel’s default — the route table’s choice for
the group address — is routinely the wrong one on a machine with a VPN or a
container bridge, in a way that presents as “the packets never arrive”.
iface is an IPv4 address for a v4 socket and an interface index for a v6
one, because that is what the two options take; "" is the default in both
cases. family() answers 4 or 6, which is how a program asks which it
should be passing.
Errors
udp.Error names AddressInUse, AddressNotAvailable, InvalidAddress,
ConnectionRefused { addr }, Unreachable { addr }, Timeout { duration_ms },
PermissionDenied, InvalidHandle, Unsupported, TooLarge,
InvalidArgument, and Other.
TooLarge has a variant of its own because it is the one datagram failure with
a specific recovery: send less, in more datagrams.
ConnectionRefused only ever arrives on a connected socket — see above.
Lifetime
udp.Socket implements Drop, so scope exit, ? propagation and cancellation
all release the socket. close() is synchronous and idempotent.
Effects
bind, connect, both receives and both sends carry Suspend. port,
family, every option, join, leave and close are synchronous: each is one
syscall answered from the socket table, so none can wait, and close being
synchronous is what lets it run from a Drop body.
Both receives keep the guest byte allocation alive across the host operation.
receive_from holds one span of guest memory, the payload’s; the sender comes
back in the answer, written when the datagram has arrived.