Scroll to navigation

CMSG(3) Manual del Programador de Linux CMSG(3)

NOMBRE

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

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

These macros are used to create and access control messages (also called ancillary data) that are not a part of the socket payload. This control information may include the interface the packet was received on, various rarely used header fields, an extended error description, a set of file descriptors or UNIX credentials. For instance, control messages can be used to send additional header fields such as IP options. Ancillary data is sent by calling sendmsg(2) and received by calling recvmsg(2). See their manual pages for more information.

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:

  • CMSG_FIRSTHDR() returns a pointer to the first cmsghdr in the ancillary data buffer associated with the passed msghdr.
  • CMSG_NXTHDR() devuelve la siguiente cmsghdr válida después de la cmsghdr pasada. Devuelve NULL cuando no queda suficiente espacio en el buffer.
  • CMSG_ALIGN(), dada una longitud, la devuelve incluyendo la alíneación necesaria. Ésta es una expresión constante.
  • CMSG_SPACE() 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.
  • CMSG_DATA() devuelve un puntero a la porción de datos de una cmsghdr.
  • CMSG_LEN() 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).

When the control message buffer is too short to store all messages, the MSG_CTRUNC flag is set in the msg_flags member of the msghdr.

CONFORME A

El modelo de datos auxiliares sigue el borrador POSIX.1003.1g, 4.4BSD-Lite, la API avanzada de IPv6 descrita en RFC 2292 y SUSv2. 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); this could be used to declare the size of global variables. This may not be portable, however.

EJEMPLO

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


struct msghdr msgh;
struct cmsghdr *cmsg;
int *ttlptr;
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) {
ttlptr = (int *) CMSG_DATA(cmsg);
received_ttl = *ttlptr;
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 */
int *fdptr;
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(int) * NUM_FD); fdptr = (int *) CMSG_DATA(cmsg); /* Initialize the payload */ memcpy(fdptr, myfds, NUM_FD * sizeof(int));

VÉASE TAMBIÉN

recvmsg(2), sendmsg(2)

RFC 2292

COLOFÓN

Esta página es parte de la versión 4.16 del proyecto Linux man-pages. Puede encontrar una descripción del proyecto, información sobre cómo informar errores y la última versión de esta página en https://www.kernel.org/doc/man-pages/.

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.

15 Septiembre 2017 Linux