Home > database >  Send and receive uint32_t over a socket via iovec
Send and receive uint32_t over a socket via iovec

Time:06-06

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?

CodePudding user response:

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

CodePudding user response:

Your code is printing the address, not the integer.

Assuming no endianess issues, then something like this should work

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

This code does assume that %d can successfully print a int32_t something I don't think is guaranteed to be true. If that's a problem you could try this

int temp = *(int32_t*)msg.msg_iov[0].iov_base;
printf("msg.msg_iov[0].iov_base = %d\n", temp);
  • Related