user3577756 user3577756 - 1 year ago 66
C++ Question

How to send a TCP buffer with different element sizes?

I am trying to send a 24 bit message between a TCP server and client.

So I have

uint8_t id = 5;
unint16_t num = 4000;

So what would be a way to send them in a TCP buffer? I know I need to convert the uint16_t into network byte order and i would not need to do that for the uint8_t.

The message I am sending has to be able to be unpaced with one of these calls as well

uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

The client is expecting a message that is comprised of a 8 bit character followed by a 16 bit number. I cannot change this so I have to work around it some how. The client will be using the above functions to convert the message as well.

As far as I know this cannot be done using one buffer. Have I over looked something?

Answer Source

You can marshall your data together by copying it into a single flat byte-buffer, like this:

uint8_t id = 5;
uint16_t num = 4000;
uint16_t beVal16 = htons(num);
unsigned char flatbuf[sizeof(id)+sizeof(beVal16)];
memcpy(&flatbuf[0], &id, sizeof(id));
memcpy(&flatbuf[sizeof(id)], &beVal16, sizeof(beVal16));
int numBytesSent = send(theSocketFD, flatbuf, sizeof(flatbuf), 0);

... and then do the reverse on the receiving side:

uint8_8 id;
uint16_t beVal16;
unsigned char flatbuf[sizeof(id)+sizeof(beVal16)];
int numBytesReceived = recv(theSocketFD, flatbuf, sizeof(flatbuf), 0);
if (numBytesReceived == sizeof(flatbuf))
   memcpy(&id, &flatbuf[0], sizeof(id));
   memcpy(&beVal16, &flatbuf[sizeof(id)], sizeof(beVal16));
   uint16_t num = ntohs(beVal16);

   printf("received num=%u id=%u\n", num, id);
else {/* handle error or partial-buffer-receive, omitted here */}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download