Reference · UDP

udp.send

signature
udp.send(str, int, any, map | null=) -> null | error(str)

What it does

Sends one UDP packet to a host and port: text as its bytes, a list of byte values (0 to 255) as those bytes, any other value as JSON. A packet holds up to 65,507 bytes. It gives null when the packet was handed to the system, and an error value when the host has no address or the system refuses the packet; UDP never says whether the packet arrived. { from: port } sends from a port the program listens on, so an answer comes back there. It needs the net effect.

Examples

print(udp.send("127.0.0.1", 9, "<14>app started"))print(udp.send("127.0.0.1", 9, [1, 2, 255]))print(udp.send("127.0.0.1", 9, { reading: 21.5, unit: "C" }))
output
nullnullnull
in a program
udp.listen(9000, (p) => print(p.text))udp.send("10.0.0.5", 9000, "hello", { from: 9000 })     // the answer comes to port 9000

Edge cases

print(udp.send("localhost", 9, "named host"))print(udp.send("::1", 9, "v6"))print(udp.send("127.0.0.1", 9, []), udp.send("127.0.0.1", 9, ""), udp.send("127.0.0.1", 9, 42))print(udp.send("not a host", 514, "x"))
output
nullnullnull null nullerr("cannot find the address of not a host")

Errors

A host with no address, or a packet the system refuses, is an error value: check it with is_err or replace it with ??. A host that is not a string, a port outside 1 to 65535, null data, more than 65,507 bytes, and a from port the program does not listen on are runtime errors.

let r = udp.send("not a host", 514, "x")print(is_err(r), r.error)print(udp.send("not a host", 514, "x") ?? "not sent")
output
true cannot find the address of not a hostnot sent
this one fails
print(udp.send("127.0.0.1", 9, null))
output
line 1: `udp.send` has nothing to send
this one fails
print(udp.send("127.0.0.1", 9, repeat("x", 65508)))
output
line 1: `udp.send`: 65508 bytes is more than a UDP packet holds (65507)
this one fails
print(udp.send("127.0.0.1", 9, "x", { from: 9999 }))
output
line 1: `udp.send`: the program does not listen on UDP port 9999

Chaining

The host comes first, so a pipeline passes it; the data is written in the call. The result is null or an error, so ? passes a failure on and ?? ignores it.

print(["127.0.0.1", "::1"] | map((h) => udp.send(h, 9, "ping")))print("127.0.0.1" | udp.send(9, "piped"))
output
[null, null]null

See also

udp.reply, udp.listen, json.stringify, is_err

Thread
5Useful? Like it, or add to its thread below.

Thread 0 posts

On udp.send(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo