Search code examples
c++socketsunix-socket

Send and receive uint32_t over a socket via iovec


I'm trying to send a uint_32t type variable over iovec sturct over unix domain socket.

My iovec declaration:

uint32_t request_id = 123456;
struct iovec io = { .iov_base = &request_id, .iov_len = sizeof(uint32_t) };

on the receiving side:

char dup[4];
struct iovec io = { .iov_base = dup, .iov_len = sizeof(dup) };
msg.msg_iov = &io;

When I print msg.msg_iov[0].iov_base I get a different number every time.

printf("msg.msg_iov[0].iov_base = %d\n", msg.msg_iov[0].iov_base); => 723905316

I guess something is off with bytes-to-uint32 conversion?


Solution

  • When I print msg.msg_iov[0].iov_base I get a different number every time.

    Yes, on the sending side it's the address of request_id and on the receiving side it's address of dup. These addresses do however not matter. They are only used to tell writev and readv where to read/write the data and they will often be different each time you start the programs.

    Example:

    Sender:

    uint32_t request_id = htonl(123456); // to network byte order from host byte order
    iovec io = { .iov_base = &request_id, .iov_len = sizeof(uint32_t) };
    writev(fd, &io, 1);
    

    Receiver:

    uint32_t request_id;
    iovec io = { .iov_base = &request_id, .iov_len = sizeof(uint32_t) };
    readv(fd, &io, 1);
    request_id = ntohl(request_id); // from network byte order to host byte order