| Updated: October 28, 2024 | 
Receive a message and its header from a socket
#include <sys/types.h>
#include <sys/socket.h>
ssize_t recvmsg( int s,
                 struct msghdr * msg,
                 int flags );
The recvmsg() routine receives a message from a socket, s, whether or not it's connection-oriented.
The recvmsg() call uses a msghdr structure to minimize the number of directly supplied parameters. This structure, defined in <sys/socket.h>, has the following form:
struct msghdr {
        void            *msg_name;      /* optional address */
        socklen_t       msg_namelen;    /* size of address */
        struct iovec    *msg_iov;       /* scatter/gather array */
        int             msg_iovlen;     /* # elements in msg_iov */
        void            *msg_control;   /* ancillary data, see below */
        socklen_t       msg_controllen; /* ancillary data buffer len */
        int             msg_flags;      /* flags on received message */
};
The msg_name and msg_namelen parameters specify the address (source address for recvmsg(); destination address for sendmsg()) if the socket is unconnected; the msg_name parameter may be given as a null pointer if no names are desired or required.
The msg_iov and msg_iovlen parameters describe scatter-gather locations, as discussed in read().
The msg_control parameter, whose length is determined by msg_controllen, points to a buffer for other protocol-control related messages or for other miscellaneous ancillary data. The messages are of the form:
struct cmsghdr {
        socklen_t       cmsg_len;       /* data byte count, including hdr */
        int             cmsg_level;     /* originating protocol */
        int             cmsg_type;      /* protocol-specific type */
        /* followed by  unsigned char  cmsg_data[]; */
};
With recvmsg() and recvmmsg(), the length in msg_controllen must not exceed SSIZE_MAX (see <limits.h>), or the function fails and sets errno to EOVERFLOW. With sendmsg() or sendmmsg(), msg_controllen must not exceed SSIZE_MAX - sizeof(_io_sock_sendto) - sizeof(socklen_t), or EOVERFLOW occurs.
The msg_flags field is set on return according to the message received:
The number of bytes received, or -1 if an error occurs (errno is set).
| Safety: | |
|---|---|
| Cancellation point | Yes | 
| Interrupt handler | No | 
| Signal handler | No | 
| Thread | Yes |