Reputation: 3
I must send a struct between two machines via a udp socket the information I need is to send a structure as follows:
unsigned long x;
unsigned long y;
char *buf;
I have to send the struct in a single time.
My problem is: How can I handle this structure to, for example, set in one variable that I can send through the socket, especially as the size of the variable buf is not fixed
Thank you for your help
Upvotes: 0
Views: 3383
Reputation: 21351
You will need to copy everything within your struct sequentially into a separate char buffer and then write that to the socket. Optionially, because your char* buffer inside your struct is not of fixed length it is often a good idea to calculate the size of what you want to send and also write this as an integer at the start of your message so that at the other end the length of the packet that you are sending can be verified by your receiving socket.
When unpacking the data at the other end, simply start at the beginning of your receive buffer and memcpy data into your values
char* message; // This is the pointer to the start of your // received message buffer
// TODO: assign message to point at start of your received buffer.
unsigned long xx;
unsigned long yy;
memcpy(&xx,message,sizeof(unsigned long)); // copy bytes of message to xx
message += sizeof(unsigned long); // move pointer to where yy SHOULD BE
// within your packet
memcpy(&yy,nessage,sizeof(unsigned long)); // copy bytes to yy
message += sizeof(unsigned long); // message now points to start of
// the string part of your message
int iStringLength = // ?????? You need to calculate length of the string
char tempBuffer[1000]; // create a temp buffer this is just for illustration
// as 1000 may not be large enough - depends on how long
// the string is
memcpy(tempBuffer,message,iStringLength);
Then xx,yy contain your long values and tempBuffer contains the string. If you want the string to persist beyond the current scope then you will need to allocate some memory and copy it there. You can calculate the size of this string from the size of the whole message minus the size of the 2 unsigned long items (or using an extra item sent in your packet IF you did as I suggested above).
I hope this clarifies what you need to do
Upvotes: 1
Reputation: 182744
You can't send a pointer, it makes no sense outside your process space. Instead, you have to serialize it, i.e. copy to an array and send that. And before the string you also need to store its length. You can try:
char sendbuf[...];
int len = strlen(buf);
memcpy(sendbuf, &x, sizeof(x));
memcpy(sendbuf + sizeof(x), &y, sizeof(y));
memcpy(sendbuf + ..., &len, sizeof(len));
memcpy(sendbuf + ..., buf, len);
Upvotes: 2