I have the following struct and I’m trying to send over the network to another application
struct protocol
{
char protocol;
char field1;
char field2;
char field3;
char field4;
char field5;
char field6;
char field7;
char field8;
char msg_id;
char msg_length;
char *msg;
};
The problem I’m having is that I’m not sure how to send this struct over the network as there is a pointer pointing to a string in it, and memcpy the struct to buffer won’t work, is the below the only way to do it?
memcpy (buffer, protocol->protocol, char)
memcpy (buffer, protocol->field1, char)
...
memcpy (buffer, protocol->msg, protocol->length)
then send the buffer
You will need to serialize the structure into a buffer of some sort. Your sequence of copies is correct in concept only; there are a myriad details to resolve:
Now you can write the correct length of buffer (
11 + protocol->msg_len) to send.This is particularly simple; there are no endian-ness issues to worry about. Generally, with multi-byte values like
shortorintorlong long, you have to worry about the transmitted byte order.