Scroll to navigation

CMSG(3) Library Functions Manual CMSG(3)

NOMBRE

CMSG_ALIGN, CMSG_SPACE, CMSG_NXTHDR, CMSG_FIRSTHDR - acceso a datos auxiliares

BIBLIOTECA

Biblioteca Estándar C (libc, -lc)

SINOPSIS

#include <sys/socket.h>
struct cmsghdr *CMSG_FIRSTHDR(struct msghdr *msgh);
struct cmsghdr *CMSG_NXTHDR(struct msghdr *msgh,
                            struct cmsghdr *cmsg);
size_t CMSG_ALIGN(size_t length);
size_t CMSG_SPACE(size_t length);
size_t CMSG_LEN(size_t length);
unsigned char *CMSG_DATA(struct cmsghdr *cmsg);

DESCRIPCIÓN

Estas macros se usan para crear y acceder a mensajes de control (también llamados datos auxiliares) que no son parte del contenido útil de un conector. Esta información de control puede incluir la interfaz en la que se ha recibido el paquete, diferentes campos de cabecera usados raramente, una descripción de error ampliada, un conjunto de descriptores de fichero o credenciales de UNIX. Por ejemplo, los mensajes de control se pueden usar para enviar campos de cabecera adicionales tales como opciones IP. Los datos auxiliares se envían llamando a sendmsg(2) y se reciben llamando a recvmsg(2). Vea sus páginas de manual para más información.

Los datos auxiliares son una secuencia de estructuras cmsghdr con datos añadidos. Vea las páginas de manual específicas del protocolo para conocer los tipos de mensajes de control disponibles. El tamaño máximo permitido del buffer auxiliar por conector se puede configura con /proc/sys/net/core/optmem_max. Vea socket(7).

The cmsghdr structure is defined as follows:


struct cmsghdr {

size_t cmsg_len; /* recuento de byte de datos incluyendo cabeceras
(el tipo en POSIX es socklen_t) */
int cmsg_level; /* Protocolo origen */
int cmsg_type; /* tipo específico de protocol */ /* Seguido por
unsigned char cmsg_data[]; */ };

The sequence of cmsghdr structures should never be accessed directly. Instead, use only the following macros:

devuelve un puntero a la primera cmsghdr en el buffer de datos auxiliares asociado con la msghdr pasada. Devolverá NULL si no se dispone de suficiente espacio para una cmsghdr en el buffer.
devuelve la siguiente cmsghdr válida después de la cmsghdr pasada. Devuelve NULL cuando no queda suficiente espacio en el buffer.
When initializing a buffer that will contain a series of cmsghdr structures (e.g., to be sent with sendmsg(2)), that buffer should first be zero-initialized to ensure the correct operation of CMSG_NXTHDR().
CMSG_ALIGN(), dada una longitud, la devuelve incluyendo la alíneación necesaria. Ésta es una expresión constante.
devuelve la cantidad de bytes que ocupa un elemento auxiliar cuyo contenido útil es de la longitud de datos pasada. Ésta es una expresión constante.
returns a pointer to the data portion of a cmsghdr. The pointer returned cannot be assumed to be suitably aligned for accessing arbitrary payload data types. Applications should not cast it to a pointer type matching the payload, but should instead use memcpy(3) to copy data to or from a suitably declared object.
devuelve el valor a almacenar en el miembro cmsg_len de la estructura cmsghdr teniendo en cuenta cualquier alíneación necesaria. Toma como argumento la longitud de los datos. Ésta es una expresión constante.

Para crear datos auxiliares, inicialice primero el miembro msg_controllen de la estructura msghdr con el tamaño del buffer de mensajes de control. Use CMSG_FIRSTHDR() sobre msghdr para obtener el primer mensaje de control y CMSG_NXTHDR() para obtener los siguientes. En cada mensaje de control, inicialice cmsg_len (con CMSG_LEN()), los otros campos cabecera de cmsghdr y la parte de datos usando CMSG_DATA(). Finalmente, debería asignar al campo msg_controllen de msghdr la suma de los CMSG_SPACE() de las longitudes de todos los mensajes de control del buffer. Para más información sobre msghdr, vea recvmsg(2).

ESTÁNDARES

This ancillary data model conforms to the POSIX.1g draft, 4.4BSD-Lite, the IPv6 advanced API described in RFC 2292 and SUSv2. CMSG_FIRSTHDR(), CMSG_NXTHDR(), and CMSG_DATA() are specified in POSIX.1-2008. CMSG_SPACE() and CMSG_LEN() will be included in the next POSIX release (Issue 8).

CMSG_ALIGN() es una extensión de Linux.

NOTAS

Para transportabilidad, sólo se debería acceder a los datos auxiliares usando las macros descritas aquí. CMSG_ALIGN() es una extensión de Linux y no debería usarse en programas transportables.

In Linux, CMSG_LEN(), CMSG_DATA(), and CMSG_ALIGN() are constant expressions (assuming their argument is constant), meaning that these values can be used to declare the size of global variables. This may not be portable, however.

EJEMPLOS

Este código busca la opción IP_TTL en un buffer auxiliar recibido:


struct msghdr msgh;
struct cmsghdr *cmsg;
int received_ttl;
/* Recibir los datos auxiliares en msgh */
for (cmsg = CMSG_FIRSTHDR(&msgh); cmsg != NULL;

cmsg = CMSG_NXTHDR(&msgh, cmsg)) {
if (cmsg->cmsg_level == IPPROTO_IP
&& cmsg->cmsg_type == IP_TTL) {
memcpy(&receive_ttl, CMSG_DATA(cmsg), sizeof(received_ttl));
break;
} } if (cmsg == NULL) {
/* Error: Error: IP_TTL no habilitada o buffer pequeño o error de E/S. */ }

The code below passes an array of file descriptors over a UNIX domain socket using SCM_RIGHTS:


struct msghdr msg = { 0 };
struct cmsghdr *cmsg;
int myfds[NUM_FD];  /* Contains the file descriptors to pass */
char iobuf[1];
struct iovec io = {

.iov_base = iobuf,
.iov_len = sizeof(iobuf) }; union { /* Ancillary data buffer, wrapped in a union
in order to ensure it is suitably aligned */
char buf[CMSG_SPACE(sizeof(myfds))];
struct cmsghdr align; } u; msg.msg_iov = &io; msg.msg_iovlen = 1; msg.msg_control = u.buf; msg.msg_controllen = sizeof(u.buf); cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(myfds)); memcpy(CMSG_DATA(cmsg), myfds, sizeof(myfds));

For a complete code example that shows passing of file descriptors over a UNIX domain socket, see seccomp_unotify(2).

VÉASE TAMBIÉN

recvmsg(2), sendmsg(2)

RFC 2292

TRADUCCIÓN

La traducción al español de esta página del manual fue creada por Juan Piernas <piernas@ditec.um.es> y Marcos Fouces <marcos@debian.org>

Esta traducción es documentación libre; lea la GNU General Public License Version 3 o posterior con respecto a las condiciones de copyright. No existe NINGUNA RESPONSABILIDAD.

Si encuentra algún error en la traducción de esta página del manual, envíe un correo electrónico a debian-l10n-spanish@lists.debian.org.

29 Octubre 2022 Páginas de manual de Linux 6.03