xref: /libuv/docs/src/udp.rst (revision d05ed869)
1
2.. _udp:
3
4:c:type:`uv_udp_t` --- UDP handle
5=================================
6
7UDP handles encapsulate UDP communication for both clients and servers.
8
9
10Data types
11----------
12
13.. c:type:: uv_udp_t
14
15    UDP handle type.
16
17.. c:type:: uv_udp_send_t
18
19    UDP send request type.
20
21.. c:type:: uv_udp_flags
22
23    Flags used in :c:func:`uv_udp_bind` and :c:type:`uv_udp_recv_cb`..
24
25    ::
26
27        enum uv_udp_flags {
28            /* Disables dual stack mode. */
29            UV_UDP_IPV6ONLY = 1,
30            /*
31            * Indicates message was truncated because read buffer was too small. The
32            * remainder was discarded by the OS. Used in uv_udp_recv_cb.
33            */
34            UV_UDP_PARTIAL = 2,
35            /*
36            * Indicates if SO_REUSEADDR will be set when binding the handle in
37            * uv_udp_bind.
38            * This sets the SO_REUSEPORT socket flag on the BSDs and OS X. On other
39            * Unix platforms, it sets the SO_REUSEADDR flag. What that means is that
40            * multiple threads or processes can bind to the same address without error
41            * (provided they all set the flag) but only the last one to bind will receive
42            * any traffic, in effect "stealing" the port from the previous listener.
43            */
44            UV_UDP_REUSEADDR = 4,
45            /*
46             * Indicates that the message was received by recvmmsg, so the buffer provided
47             * must not be freed by the recv_cb callback.
48             */
49            UV_UDP_MMSG_CHUNK = 8,
50            /*
51             * Indicates that the buffer provided has been fully utilized by recvmmsg and
52             * that it should now be freed by the recv_cb callback. When this flag is set
53             * in uv_udp_recv_cb, nread will always be 0 and addr will always be NULL.
54             */
55            UV_UDP_MMSG_FREE = 16,
56            /*
57             * Indicates if IP_RECVERR/IPV6_RECVERR will be set when binding the handle.
58             * This sets IP_RECVERR for IPv4 and IPV6_RECVERR for IPv6 UDP sockets on
59             * Linux. This stops the Linux kernel from suppressing some ICMP error messages
60             * and enables full ICMP error reporting for faster failover.
61             * This flag is no-op on platforms other than Linux.
62             */
63            UV_UDP_LINUX_RECVERR = 32,
64            /*
65            * Indicates that recvmmsg should be used, if available.
66            */
67            UV_UDP_RECVMMSG = 256
68        };
69
70.. c:type:: void (*uv_udp_send_cb)(uv_udp_send_t* req, int status)
71
72    Type definition for callback passed to :c:func:`uv_udp_send`, which is
73    called after the data was sent.
74
75.. c:type:: void (*uv_udp_recv_cb)(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags)
76
77    Type definition for callback passed to :c:func:`uv_udp_recv_start`, which
78    is called when the endpoint receives data.
79
80    * `handle`: UDP handle
81    * `nread`:  Number of bytes that have been received.
82      0 if there is no more data to read. Note that 0 may also mean that an
83      empty datagram was received (in this case `addr` is not NULL). < 0 if
84      a transmission error was detected; if using :man:`recvmmsg(2)` no more
85      chunks will be received and the buffer can be freed safely.
86    * `buf`: :c:type:`uv_buf_t` with the received data.
87    * `addr`: ``struct sockaddr*`` containing the address of the sender.
88      Can be NULL. Valid for the duration of the callback only.
89    * `flags`: One or more or'ed UV_UDP_* constants.
90
91    The callee is responsible for freeing the buffer, libuv does not reuse it.
92    The buffer may be a null buffer (where `buf->base` == NULL and `buf->len` == 0)
93    on error.
94
95    When using :man:`recvmmsg(2)`, chunks will have the `UV_UDP_MMSG_CHUNK` flag set,
96    those must not be freed. If no errors occur, there will be a final callback with
97    `nread` set to 0, `addr` set to NULL and the buffer pointing at the initially
98    allocated data with the `UV_UDP_MMSG_CHUNK` flag cleared and the `UV_UDP_MMSG_FREE`
99    flag set. If a UDP socket error occurs, `nread` will be < 0. In either scenario,
100    the callee can now safely free the provided buffer.
101
102    .. versionchanged:: 1.40.0 added the `UV_UDP_MMSG_FREE` flag.
103
104    .. note::
105        The receive callback will be called with `nread` == 0 and `addr` == NULL when there is
106        nothing to read, and with `nread` == 0 and `addr` != NULL when an empty UDP packet is
107        received.
108
109.. c:enum:: uv_membership
110
111    Membership type for a multicast address.
112
113    ::
114
115        typedef enum {
116            UV_LEAVE_GROUP = 0,
117            UV_JOIN_GROUP
118        } uv_membership;
119
120
121Public members
122^^^^^^^^^^^^^^
123
124.. c:member:: size_t uv_udp_t.send_queue_size
125
126    Number of bytes queued for sending. This field strictly shows how much
127    information is currently queued.
128
129.. c:member:: size_t uv_udp_t.send_queue_count
130
131    Number of send requests currently in the queue awaiting to be processed.
132
133.. c:member:: uv_udp_t* uv_udp_send_t.handle
134
135    UDP handle where this send request is taking place.
136
137.. seealso:: The :c:type:`uv_handle_t` members also apply.
138
139
140API
141---
142
143.. c:function:: int uv_udp_init(uv_loop_t* loop, uv_udp_t* handle)
144
145    Initialize a new UDP handle. The actual socket is created lazily.
146    Returns 0 on success.
147
148.. c:function:: int uv_udp_init_ex(uv_loop_t* loop, uv_udp_t* handle, unsigned int flags)
149
150    Initialize the handle with the specified flags. The lower 8 bits of the `flags`
151    parameter are used as the socket domain. A socket will be created for the given domain.
152    If the specified domain is ``AF_UNSPEC`` no socket is created, just like :c:func:`uv_udp_init`.
153
154    The remaining bits can be used to set one of these flags:
155
156    * `UV_UDP_RECVMMSG`: if set, and the platform supports it, :man:`recvmmsg(2)` will
157      be used.
158
159    .. versionadded:: 1.7.0
160    .. versionchanged:: 1.37.0 added the `UV_UDP_RECVMMSG` flag.
161
162.. c:function:: int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock)
163
164    Opens an existing file descriptor or Windows SOCKET as a UDP handle.
165
166    Unix only:
167    The only requirement of the `sock` argument is that it follows the datagram
168    contract (works in unconnected mode, supports sendmsg()/recvmsg(), etc).
169    In other words, other datagram-type sockets like raw sockets or netlink
170    sockets can also be passed to this function.
171
172    .. versionchanged:: 1.2.1 the file descriptor is set to non-blocking mode.
173
174    .. note::
175        The passed file descriptor or SOCKET is not checked for its type, but
176        it's required that it represents a valid datagram socket.
177
178.. c:function:: int uv_udp_bind(uv_udp_t* handle, const struct sockaddr* addr, unsigned int flags)
179
180    Bind the UDP handle to an IP address and port.
181
182    :param handle: UDP handle. Should have been initialized with
183        :c:func:`uv_udp_init`.
184
185    :param addr: `struct sockaddr_in` or `struct sockaddr_in6`
186        with the address and port to bind to.
187
188    :param flags: Indicate how the socket will be bound,
189        ``UV_UDP_IPV6ONLY``, ``UV_UDP_REUSEADDR``, and ``UV_UDP_RECVERR``
190        are supported.
191
192    :returns: 0 on success, or an error code < 0 on failure.
193
194.. c:function:: int uv_udp_connect(uv_udp_t* handle, const struct sockaddr* addr)
195
196    Associate the UDP handle to a remote address and port, so every
197    message sent by this handle is automatically sent to that destination.
198    Calling this function with a `NULL` `addr` disconnects the handle.
199    Trying to call `uv_udp_connect()` on an already connected handle will result
200    in an `UV_EISCONN` error. Trying to disconnect a handle that is not
201    connected will return an `UV_ENOTCONN` error.
202
203    :param handle: UDP handle. Should have been initialized with
204        :c:func:`uv_udp_init`.
205
206    :param addr: `struct sockaddr_in` or `struct sockaddr_in6`
207        with the address and port to associate to.
208
209    :returns: 0 on success, or an error code < 0 on failure.
210
211    .. versionadded:: 1.27.0
212
213.. c:function:: int uv_udp_getpeername(const uv_udp_t* handle, struct sockaddr* name, int* namelen)
214
215    Get the remote IP and port of the UDP handle on connected UDP handles.
216    On unconnected handles, it returns `UV_ENOTCONN`.
217
218    :param handle: UDP handle. Should have been initialized with
219        :c:func:`uv_udp_init` and bound.
220
221    :param name: Pointer to the structure to be filled with the address data.
222        In order to support IPv4 and IPv6 `struct sockaddr_storage` should be
223        used.
224
225    :param namelen: On input it indicates the data of the `name` field. On
226        output it indicates how much of it was filled.
227
228    :returns: 0 on success, or an error code < 0 on failure
229
230    .. versionadded:: 1.27.0
231
232.. c:function:: int uv_udp_getsockname(const uv_udp_t* handle, struct sockaddr* name, int* namelen)
233
234    Get the local IP and port of the UDP handle.
235
236    :param handle: UDP handle. Should have been initialized with
237        :c:func:`uv_udp_init` and bound.
238
239    :param name: Pointer to the structure to be filled with the address data.
240        In order to support IPv4 and IPv6 `struct sockaddr_storage` should be
241        used.
242
243    :param namelen: On input it indicates the data of the `name` field. On
244        output it indicates how much of it was filled.
245
246    :returns: 0 on success, or an error code < 0 on failure.
247
248.. c:function:: int uv_udp_set_membership(uv_udp_t* handle, const char* multicast_addr, const char* interface_addr, uv_membership membership)
249
250    Set membership for a multicast address
251
252    :param handle: UDP handle. Should have been initialized with
253        :c:func:`uv_udp_init`.
254
255    :param multicast_addr: Multicast address to set membership for.
256
257    :param interface_addr: Interface address.
258
259    :param membership: Should be ``UV_JOIN_GROUP`` or ``UV_LEAVE_GROUP``.
260
261    :returns: 0 on success, or an error code < 0 on failure.
262
263.. c:function:: int uv_udp_set_source_membership(uv_udp_t* handle, const char* multicast_addr, const char* interface_addr, const char* source_addr, uv_membership membership)
264
265    Set membership for a source-specific multicast group.
266
267    :param handle: UDP handle. Should have been initialized with
268        :c:func:`uv_udp_init`.
269
270    :param multicast_addr: Multicast address to set membership for.
271
272    :param interface_addr: Interface address.
273
274    :param source_addr: Source address.
275
276    :param membership: Should be ``UV_JOIN_GROUP`` or ``UV_LEAVE_GROUP``.
277
278    :returns: 0 on success, or an error code < 0 on failure.
279
280    .. versionadded:: 1.32.0
281
282.. c:function:: int uv_udp_set_multicast_loop(uv_udp_t* handle, int on)
283
284    Set IP multicast loop flag. Makes multicast packets loop back to
285    local sockets.
286
287    :param handle: UDP handle. Should have been initialized with
288        :c:func:`uv_udp_init_ex` as either ``AF_INET`` or ``AF_INET6``, or have
289        been bound to an address explicitly with :c:func:`uv_udp_bind`, or
290        implicitly with :c:func:`uv_udp_send()` or :c:func:`uv_udp_recv_start`.
291
292    :param on: 1 for on, 0 for off.
293
294    :returns: 0 on success, or an error code < 0 on failure.
295
296.. c:function:: int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl)
297
298    Set the multicast ttl.
299
300    :param handle: UDP handle. Should have been initialized with
301        :c:func:`uv_udp_init_ex` as either ``AF_INET`` or ``AF_INET6``, or have
302        been bound to an address explicitly with :c:func:`uv_udp_bind`, or
303        implicitly with :c:func:`uv_udp_send()` or :c:func:`uv_udp_recv_start`.
304
305    :param ttl: 1 through 255.
306
307    :returns: 0 on success, or an error code < 0 on failure.
308
309.. c:function:: int uv_udp_set_multicast_interface(uv_udp_t* handle, const char* interface_addr)
310
311    Set the multicast interface to send or receive data on.
312
313    :param handle: UDP handle. Should have been initialized with
314        :c:func:`uv_udp_init_ex` as either ``AF_INET`` or ``AF_INET6``, or have
315        been bound to an address explicitly with :c:func:`uv_udp_bind`, or
316        implicitly with :c:func:`uv_udp_send()` or :c:func:`uv_udp_recv_start`.
317
318    :param interface_addr: interface address.
319
320    :returns: 0 on success, or an error code < 0 on failure.
321
322.. c:function:: int uv_udp_set_broadcast(uv_udp_t* handle, int on)
323
324    Set broadcast on or off.
325
326    :param handle: UDP handle. Should have been initialized with
327        :c:func:`uv_udp_init_ex` as either ``AF_INET`` or ``AF_INET6``, or have
328        been bound to an address explicitly with :c:func:`uv_udp_bind`, or
329        implicitly with :c:func:`uv_udp_send()` or :c:func:`uv_udp_recv_start`.
330
331    :param on: 1 for on, 0 for off.
332
333    :returns: 0 on success, or an error code < 0 on failure.
334
335.. c:function:: int uv_udp_set_ttl(uv_udp_t* handle, int ttl)
336
337    Set the time to live.
338
339    :param handle: UDP handle. Should have been initialized with
340        :c:func:`uv_udp_init_ex` as either ``AF_INET`` or ``AF_INET6``, or have
341        been bound to an address explicitly with :c:func:`uv_udp_bind`, or
342        implicitly with :c:func:`uv_udp_send()` or :c:func:`uv_udp_recv_start`.
343
344    :param ttl: 1 through 255.
345
346    :returns: 0 on success, or an error code < 0 on failure.
347
348.. c:function:: int uv_udp_send(uv_udp_send_t* req, uv_udp_t* handle, const uv_buf_t bufs[], unsigned int nbufs, const struct sockaddr* addr, uv_udp_send_cb send_cb)
349
350    Send data over the UDP socket. If the socket has not previously been bound
351    with :c:func:`uv_udp_bind` it will be bound to 0.0.0.0
352    (the "all interfaces" IPv4 address) and a random port number.
353
354    On Windows if the `addr` is initialized to point to an unspecified address
355    (``0.0.0.0`` or ``::``) it will be changed to point to ``localhost``.
356    This is done to match the behavior of Linux systems.
357
358    For connected UDP handles, `addr` must be set to `NULL`, otherwise it will
359    return `UV_EISCONN` error.
360
361    For connectionless UDP handles, `addr` cannot be `NULL`, otherwise it will
362    return `UV_EDESTADDRREQ` error.
363
364    :param req: UDP request handle. Need not be initialized.
365
366    :param handle: UDP handle. Should have been initialized with
367        :c:func:`uv_udp_init`.
368
369    :param bufs: List of buffers to send.
370
371    :param nbufs: Number of buffers in `bufs`.
372
373    :param addr: `struct sockaddr_in` or `struct sockaddr_in6` with the
374        address and port of the remote peer.
375
376    :param send_cb: Callback to invoke when the data has been sent out.
377
378    :returns: 0 on success, or an error code < 0 on failure.
379
380    .. versionchanged:: 1.19.0 added ``0.0.0.0`` and ``::`` to ``localhost``
381        mapping
382
383    .. versionchanged:: 1.27.0 added support for connected sockets
384
385.. c:function:: int uv_udp_try_send(uv_udp_t* handle, const uv_buf_t bufs[], unsigned int nbufs, const struct sockaddr* addr)
386
387    Same as :c:func:`uv_udp_send`, but won't queue a send request if it can't
388    be completed immediately.
389
390    For connected UDP handles, `addr` must be set to `NULL`, otherwise it will
391    return `UV_EISCONN` error.
392
393    For connectionless UDP handles, `addr` cannot be `NULL`, otherwise it will
394    return `UV_EDESTADDRREQ` error.
395
396    :returns: >= 0: number of bytes sent (it matches the given buffer size).
397        < 0: negative error code (``UV_EAGAIN`` is returned when the message
398        can't be sent immediately).
399
400    .. versionchanged:: 1.27.0 added support for connected sockets
401
402.. c:function:: int uv_udp_recv_start(uv_udp_t* handle, uv_alloc_cb alloc_cb, uv_udp_recv_cb recv_cb)
403
404    Prepare for receiving data. If the socket has not previously been bound
405    with :c:func:`uv_udp_bind` it is bound to 0.0.0.0 (the "all interfaces"
406    IPv4 address) and a random port number.
407
408    :param handle: UDP handle. Should have been initialized with
409        :c:func:`uv_udp_init`.
410
411    :param alloc_cb: Callback to invoke when temporary storage is needed.
412
413    :param recv_cb: Callback to invoke with received data.
414
415    :returns: 0 on success, or an error code < 0 on failure.
416
417    .. note::
418        When using :man:`recvmmsg(2)`, the number of messages received at a time is limited
419        by the number of max size dgrams that will fit into the buffer allocated in `alloc_cb`, and
420        `suggested_size` in `alloc_cb` for udp_recv is always set to the size of 1 max size dgram.
421
422    .. versionchanged:: 1.35.0 added support for :man:`recvmmsg(2)` on supported platforms).
423                        The use of this feature requires a buffer larger than
424                        2 * 64KB to be passed to `alloc_cb`.
425    .. versionchanged:: 1.37.0 :man:`recvmmsg(2)` support is no longer enabled implicitly,
426                        it must be explicitly requested by passing the `UV_UDP_RECVMMSG` flag to
427                        :c:func:`uv_udp_init_ex`.
428    .. versionchanged:: 1.39.0 :c:func:`uv_udp_using_recvmmsg` can be used in `alloc_cb` to
429                        determine if a buffer sized for use with :man:`recvmmsg(2)` should be
430                        allocated for the current handle/platform.
431
432.. c:function:: int uv_udp_using_recvmmsg(uv_udp_t* handle)
433
434    Returns 1 if the UDP handle was created with the `UV_UDP_RECVMMSG` flag
435    and the platform supports :man:`recvmmsg(2)`, 0 otherwise.
436
437    .. versionadded:: 1.39.0
438
439.. c:function:: int uv_udp_recv_stop(uv_udp_t* handle)
440
441    Stop listening for incoming datagrams.
442
443    :param handle: UDP handle. Should have been initialized with
444        :c:func:`uv_udp_init`.
445
446    :returns: 0 on success, or an error code < 0 on failure.
447
448.. c:function:: size_t uv_udp_get_send_queue_size(const uv_udp_t* handle)
449
450    Returns `handle->send_queue_size`.
451
452    .. versionadded:: 1.19.0
453
454.. c:function:: size_t uv_udp_get_send_queue_count(const uv_udp_t* handle)
455
456    Returns `handle->send_queue_count`.
457
458    .. versionadded:: 1.19.0
459
460.. seealso:: The :c:type:`uv_handle_t` API functions also apply.
461