Hi, I need to send different structures through the network, and be able to recover them at the other side. I do not know how to give each structure an unique identifier, so I can discover what is the structure after receiving it. The receiver will be waiting for specific structures, the problem is that the structures can arrive in any order, or some of them do not arrive at all, for example:
Code:
structure Basic {
/* data */
};
structure AdvancedOne {
/* data */
};
structure AdvancedTwo {
/* data */
};
/* Generates data to the receiver */
void sender()
{
Basic b;
AdvancedTwo at;
/* Initialize */
char socket_buffer[MAX_SIZE];
int current_size = 0;
pack(&b, sizeof(b), socket_buffer, ¤t_size);
pack(&at, sizeof(at), socket_buffer, ¤t_size);
send(sock_fd, socket_buffer, current_size);
}
/* Decode data, it will be waiting for Basic and AdvancedOne */
void receiver()
{
char buffer[MAX_SIZE];
recv(sock_fd, buffer, sizeof(buffer), 0);
Basic b;
AdvancedOne ao;
unpack(&b, sizeof(b), buffer);
unpack(&ao, sizeof(ao), buffer); // Will generate an erro, that's ok, AdvOne was not sent
}
The unpack function would rely on the first 4 bytes (an int) to know what is unpacking (the identifier). My problem is that I do not know what is the best way to assign this ID. I could have specific pack functions for each type of structure, but, if possible, I would like to have only a pack function like:
Code:
void pack(void*, int, char*, int);
In C++ I would perform something like:
Code:
struct B {
static int ID;
};
int B::ID = 0;
Any suggestions?