I'm writing code that deals with data received from the UDP protocol in the application layer.
This is the function prototype used to receive data from the UDP protocol:
int my_recv_UDP(int s,
void* mem,
int len,
struct sockaddr* from,
int fromlen);
in which:
s
: the socket.
mem
: received data is put in it.
len
: memory length of mem
.
This function returns the data length, which may be less than len
.
For example
frameLen = my_recv_UDP(socket, rxBuf, 100, &ra, sizeof(ra));
In which it uses socket
as the socket, stores data in rxBuf
with a length of 100
, and returns the length of received data to frameLen
.
The length of the received data may vary from 100. Since I specify a length of 100, I might receive data that is less than 100, or lose data that exceeds 100, depending on the frame.
I intended to create rxBuf_s
and let this struct type's pointer point to rxBuf.
i.e:
typedef struct{
int cmd;
int data[?]; //you don't know the data length until it's received
int len;
}rxBuf_s;
rxBuf_s* rxBuf_p = rxBuf;
With this, I can easily "manipulate" data in rxBuf. For example, if I want to read cmd into buffer, I can do this:
int Cmd = rxBuf_p->cmd;
However, I didn't know the data length until the data was received, and I didn't know what offset was for len either; So decided to calculate the length at "run time" and put it in array, like this:
typedef struct{
int cmd;
int data[length]; //length is calculated at run time.
int len;
}rxBuf_s;
But VLA in struct is not allowed in C99.
How can I handle it? Is there a smart way to do this?
So you receive cmd, data[length], len in this order in the frame. As you already noted, it is not possible to catch this 1:1 using a C structure. At least the len
field has to be extracted by a different means, e.g.
length = ...; // calculate length
int cmd = *(int*)rxBuf;
int *data = (int*)rxBuf + 1;
int len = *(data + length);