Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

net.udp

import net

Everything here is re-exported by net, so import net is enough and the names are called as net.*. Importing net.udp on its own works too and reaches the same definitions.

This module provides a complete implementation of the User Datagram Protocol as specified in IETF RFC 768. It provides an interface for sending and receiving individual datagrams, including support for broadcast and multicast delivery.

Unlike TCP, UDP is connectionless: there is no handshake, no guarantee of delivery or ordering, and no notion of a byte stream - every send or receive operates on a single, self-contained datagram.

It is meant to be used to provide more controlled and specific UDP-based operating system features and for implementing various standard and custom network protocols and specifications.

The example below shows how to use this module for a simple request/response exchange with a remote host.

import net

var socket = net.UdpSocket()
socket.connect('example.com:9000')
socket.send('ping')

echo socket.receive(512)
socket.close()

A socket can also be bound to a local address to receive datagrams from any sender, as shown below with a basic listener on port 9000.

import net

var server = net.UdpSocket()
server.bind('0.0.0.0:9000')
echo 'listening on ${server.local_address()}'

while true {
  echo 'received: ${server.receive_from(512)}'
}

Classes

UdpSocket

class net.UdpSocket

A UDP socket, usable for both sending and receiving datagrams, either to/from a single fixed peer (after connect()) or to/from arbitrary addresses (via send_to()/receive_from()/peek_from()).

Unlike a TCP stream, connect() and bind() are not mutually exclusive here: a socket may be bound to a local address and then separately connected to a default remote peer.

  • printable — has a @to_string(), so echo and print() show something useful

Note: UdpSocket.connect() only narrows which peer send()/recv() talk to and does not perform any handshake.

Note: It’s a good practice to call close() explicitly once you are done with an instance instead of relying on Zuri to release the socket for you.

Constructor

net.UdpSocket()

Returns a new instance of a UdpSocket, backed by a fresh, unbound and unconnected native socket. Use bind() to receive datagrams on a local address, and/or connect() to fix the peer used by send()/receive().

UdpSocket.connect()

net.UdpSocket.connect(address)

Connects this socket to a remote address. This does not perform a handshake - UDP is connectionless - it simply records address as the default peer for future send()/receive()/peek() calls, and filters out datagrams arriving from any other address. Calling this again re-targets the socket at a new peer.

address may be a hostname or an IP literal, combined with a port, e.g. 'example.com:9000' or '127.0.0.1:9000'. A hostname may resolve to several addresses; they are tried in turn and the first one that succeeds is used.

Parameters

  • address (string|SocketAddr) — The host:port to treat as the default peer

Raises Error if resolution fails or every resolved address is rejected

UdpSocket.bind()

net.UdpSocket.bind(address)

Binds this socket to address, allowing it to receive datagrams sent to that address.

address may be a hostname or an IP literal combined with a port, e.g. '0.0.0.0:9000' or '[::]:9000'; port 0 asks the OS to assign an available ephemeral port, which can then be discovered via local_address(). If address resolves to multiple addresses, binding is attempted against each in turn until one succeeds.

Parameters

  • address (string|SocketAddr) — The host:port to bind and receive on

Raises Error if resolution fails or every resolved address fails to bind (e.g. because it is already in use)

UdpSocket.peer_address()

net.UdpSocket.peer_address() -> SocketAddr

Returns the address of the remote peer this socket was connected to via connect().

Returns SocketAddr — the peer’s address

Raises Error if this socket has not been connected

UdpSocket.local_address()

net.UdpSocket.local_address() -> SocketAddr

Returns the local socket address of this instance. Particularly useful for discovering the actual port chosen by the OS after binding to port 0.

Returns SocketAddr — the local address

Raises Error if this socket has not been bound

UdpSocket.set_read_timeout()

net.UdpSocket.set_read_timeout(timeout)

Sets the timeout for future receive()/peek() calls.

Pass a number of milliseconds greater than 0 to bound how long a read may block before raising a timeout error, or pass 0 (or any negative number) to remove the timeout entirely and block indefinitely.

Parameters

  • timeout (number) — Milliseconds, or a negative number to disable the timeout

Raises Error if the platform rejects the value

Note: Some platforms do not provide access to the current timeout.

UdpSocket.get_read_timeout()

net.UdpSocket.get_read_timeout() -> number

Returns the currently configured read timeout in milliseconds, or -1 if no timeout is set (i.e. reads block indefinitely).

Returns number — milliseconds, or -1 if unset

UdpSocket.set_write_timeout()

net.UdpSocket.set_write_timeout(timeout)

Sets the timeout for future send() calls. Same rules as set_read_timeout(): a number of milliseconds greater than 0 bounds how long a send may block, 0 (or any negative number) disables the timeout.

Parameters

  • timeout (number) — Milliseconds, or a negative number to disable the timeout

Raises Error if the platform rejects the value

Note: A send only blocks in the first place when the OS’s outgoing socket buffer is full, which is uncommon for datagram sockets.

UdpSocket.get_write_timeout()

net.UdpSocket.get_write_timeout() -> number

Returns the currently configured write timeout in milliseconds, or -1 if no timeout is set (i.e. sends block indefinitely).

Returns number — milliseconds, or -1 if unset

UdpSocket.peek()

net.UdpSocket.peek(length) -> bytes

Peeks at the next incoming datagram from the connected peer without removing it from the socket’s receive queue - a subsequent receive()/peek() call will still see it. Defaults to peeking a single byte when length is omitted.

Requires a connected socket, since (like receive()) it only reads from the peer set via connect(). Use peek_from() on a socket that is only bound.

Parameters

  • length (number) — The maximum number of bytes to peek

Returns bytes — up to length bytes of the pending datagram

Raises Error on an underlying I/O error, or if this socket has not been connected

UdpSocket.peek_from()

net.UdpSocket.peek_from(length) -> data: bytes, address: SocketAddr

Peeks at the next incoming datagram from any sender without removing it from the socket’s receive queue - a subsequent receive_from()/peek_from() call will still see it. Defaults to peeking a single byte when length is omitted. Unlike peek(), this does not require a connected socket.

Parameters

  • length (number) — The maximum number of bytes to peek

Returns data: bytes, address: SocketAddr — the pending datagram’s bytes and the address it was sent from

Raises Error on an underlying I/O error

UdpSocket.set_ttl()

net.UdpSocket.set_ttl(ttl)

Sets IP_TTL (the IPv4 time-to-live / IPv6 hop limit) used for regular, non-multicast datagrams sent on this socket.

Parameters

  • ttl (number) — The time-to-live value, 0-255

Raises Error on an underlying I/O error

UdpSocket.get_ttl()

net.UdpSocket.get_ttl() -> number

Returns the currently configured IP_TTL value for this socket.

Returns number

Raises Error on an underlying I/O error

UdpSocket.get_error()

net.UdpSocket.get_error() -> ?string

Retrieves and clears the value of the socket’s SO_ERROR option - i.e. any pending error the OS has recorded for this socket without yet surfacing through a failed send or receive.

Returns ?string — a description of the pending error, or nil if there is none

Raises Error on an underlying I/O error while querying the socket

UdpSocket.set_non_blocking()

net.UdpSocket.set_non_blocking(nonblocking)

Puts the socket into or out of non-blocking mode. In non-blocking mode, receive()/receive_from()/send() and friends return immediately with an error instead of blocking when the operation would otherwise wait on I/O.

Parameters

  • nonblocking (bool) — true to enable non-blocking mode

Raises Error on an underlying I/O error

UdpSocket.set_broadcast()

net.UdpSocket.set_broadcast(broadcast)

Enables or disables SO_BROADCAST. This must be enabled before send_to() can deliver a datagram to a broadcast address, such as 255.255.255.255.

Parameters

  • broadcast (bool) — true to allow sending to broadcast addresses

Raises Error on an underlying I/O error

UdpSocket.get_broadcast()

net.UdpSocket.get_broadcast() -> bool

Returns whether SO_BROADCAST is currently enabled on this socket.

Returns bool

UdpSocket.set_multicast_loop_v4()

net.UdpSocket.set_multicast_loop_v4(loop)

Enables or disables IP_MULTICAST_LOOP for IPv4 multicast. When enabled (the default), multicast datagrams sent from this socket are also looped back and delivered to this same host if it has joined the destination group.

Parameters

  • loop (bool) — true to loop sent multicast datagrams back

Raises Error on an underlying I/O error

UdpSocket.get_multicast_loop_v4()

net.UdpSocket.get_multicast_loop_v4() -> bool

Returns whether IP_MULTICAST_LOOP is currently enabled for IPv4 multicast on this socket.

Returns bool

UdpSocket.set_multicast_ttl_v4()

net.UdpSocket.set_multicast_ttl_v4(ttl)

Sets IP_MULTICAST_TTL, the time-to-live used specifically for outgoing IPv4 multicast datagrams sent on this socket, independent of the regular IP_TTL set via set_ttl(). Defaults to 1, restricting multicast datagrams to the local network.

Parameters

  • ttl (number) — The multicast time-to-live value, 0-255

Raises Error on an underlying I/O error

UdpSocket.get_multicast_ttl_v4()

net.UdpSocket.get_multicast_ttl_v4() -> number

Returns the currently configured IP_MULTICAST_TTL value for IPv4 multicast on this socket.

Returns number

Raises Error on an underlying I/O error

UdpSocket.set_multicast_loop_v6()

net.UdpSocket.set_multicast_loop_v6(loop)

Enables or disables IPV6_MULTICAST_LOOP for IPv6 multicast. When enabled (the default), multicast datagrams sent from this socket are also looped back and delivered to this same host if it has joined the destination group.

Parameters

  • loop (bool) — true to loop sent multicast datagrams back

Raises Error on an underlying I/O error

UdpSocket.get_multicast_loop_v6()

net.UdpSocket.get_multicast_loop_v6() -> bool

Returns whether IPV6_MULTICAST_LOOP is currently enabled for IPv6 multicast on this socket.

Returns bool

UdpSocket.receive()

net.UdpSocket.receive(length) -> bytes

Receives a single datagram from the connected peer into a newly allocated byte buffer of up to length bytes. Requires a connected socket, since (like peek()) it only reads from the peer set via connect(). Use receive_from() on a socket that is only bound.

An empty result means an empty (zero-length) datagram was received, which is valid and distinct from there being nothing to receive.

Parameters

  • length (number) — The maximum number of bytes to read

Returns bytes — up to length bytes of the received datagram

Raises Error on an underlying I/O error, or if the configured read timeout elapses first

Note: A datagram read is all-or-nothing per message: if the incoming datagram is larger than length, the excess bytes are discarded rather than being returned on a subsequent call - this is unlike a TCP stream, where a short read just leaves the rest to be read later.

UdpSocket.receive_from()

net.UdpSocket.receive_from(length) -> bytes

Receives a single datagram from any sender into a newly allocated byte buffer of length bytes. Does not require a connected socket.

Parameters

  • length (number) — The size of the buffer to read into

Returns bytes — a length-byte buffer containing the received datagram

Raises Error on an underlying I/O error, or if the configured read timeout elapses first

Note: As with receive(), if the incoming datagram is larger than length, the excess bytes are discarded.

UdpSocket.send()

net.UdpSocket.send(data) -> number

Sends data as a single datagram to the connected peer. Requires a connected socket. Unlike a TCP stream’s write(), a successful call always sends the entirety of data as one datagram - there is no concept of a partial send here, though very large datagrams may be rejected outright depending on the platform and network path.

Parameters

  • data (bytes|string) — The bytes (or UTF-8 text) to send

Returns number — the number of bytes sent (equal to the size of data on success)

Raises Error on an underlying I/O error, or if the configured write timeout elapses first

UdpSocket.send_to()

net.UdpSocket.send_to(data, address) -> number

Sends data as a single datagram to address. Does not require a connected socket, and does not change the peer set by connect(), if any.

Parameters

  • data (bytes|string) — The bytes (or UTF-8 text) to send
  • address (string|SocketAddr) — The host:port to send the datagram to

Returns number — the number of bytes sent (equal to the size of data on success)

Raises Error on an underlying I/O error, or if the configured write timeout elapses first

UdpSocket.join_multicast_v4()

net.UdpSocket.join_multicast_v4(multiaddr, interface)

Joins the IPv4 multicast group multiaddr on the network interface identified by interface.

Parameters

  • multiaddr (string) — The multicast address to join, e.g. '239.0.0.1'
  • interface (string) — The local IPv4 address of the interface to join on, e.g. '0.0.0.0' for the default interface

Raises Error if multiaddr/interface cannot be parsed as IPv4 addresses, or on an underlying I/O error

UdpSocket.leave_multicast_v4()

net.UdpSocket.leave_multicast_v4(multiaddr, interface)

Leaves the IPv4 multicast group multiaddr on the network interface identified by interface. Both arguments must match the values originally passed to join_multicast_v4().

Parameters

  • multiaddr (string) — The multicast address to leave
  • interface (string) — The local IPv4 address of the interface to leave on

Raises Error if multiaddr/interface cannot be parsed as IPv4 addresses, or on an underlying I/O error

UdpSocket.join_multicast_v6()

net.UdpSocket.join_multicast_v6(multiaddr, interface)

Joins the IPv6 multicast group multiaddr on the network interface identified by interface.

Parameters

  • multiaddr (string) — The multicast address to join, e.g. 'ff02::1'
  • interface (number) — The index of the local interface to join on, or 0 to let the OS choose the default interface

Raises Error if multiaddr cannot be parsed as an IPv6 address, or on an underlying I/O error

UdpSocket.leave_multicast_v6()

net.UdpSocket.leave_multicast_v6(multiaddr, interface)

Leaves the IPv6 multicast group multiaddr on the network interface identified by interface. Both arguments must match the values originally passed to join_multicast_v6().

Parameters

  • multiaddr (string) — The multicast address to leave
  • interface (number) — The index of the local interface to leave on

Raises Error if multiaddr cannot be parsed as an IPv6 address, or on an underlying I/O error

UdpSocket.close()

net.UdpSocket.close()

Releases the underlying socket. It is advised to call this explicitly once you are done with the socket rather than relying on the Zuri garbage collector to do it for you eventually. Safe to call more than once, and safe to call on an instance that was never bound or connected.

UdpSocket.to_string()

net.UdpSocket.to_string() -> string

A human readable representation of this socket, showing whichever of the bound-local or connected-peer addresses apply.

Returns string


2026, Richard Ore and Zuri contributors