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.
Code
// UDP send and receive — connectionless datagrams
fn main() -> int {
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")
let msg: String = "hello via UDP"
udp_sendto(sock, msg, "127.0.0.1", 9001)
print("sent: " + msg)
let received: String = udp_recvfrom(sock, 1024)
print("received: " + received)
tcp_close(sock)
return 0
}
Output
UDP socket bound to :9001 sent: hello via UDP received: hello via UDP
Explanation
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).