Skip to content

sendmsg / recvmsg

sendmsg() and recvmsg() send and receive messages with optional ancillary data.

They are required for advanced socket features such as file descriptor passing with SCM_RIGHTS.

Prototype

#include <sys/socket.h>

ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);

Core Structures

struct msghdr {
    void         *msg_name;
    socklen_t    msg_namelen;
    struct iovec *msg_iov;
    size_t       msg_iovlen;
    void        *msg_control;
    size_t       msg_controllen;
    int          msg_flags;
};

Return Value

  • number of bytes sent or received on success
  • -1 on error, with errno set

Common Pitfalls

Warning

Always initialize struct msghdr and control buffers to zero before use.

Note

sendmsg() and recvmsg() are more verbose than send() and recv(), but they are necessary when ancillary data is involved.