[Solved] How to parse received data with variable length


One approach is to define a packed struct which represents the largest possible packet size:

#pragma pack(push,1) // make sure everything is packed to byte level
typedef struct {
    uint8_t        Length;
    uint8_t        SrcArsDev;
    uint32_t       Src_ID;
    uint8_t        DstArsDev;
    uint32_t       Dst_ID;
    uint32_t       Session;
    uint8_t        CMD;
    uint8_t        payload[96 + 2]; // payload + CRC
} Message;
#pragma pack(pop)    // restore struct packing

Your read routine then reads directly to such a struct, and then all the elements of the message can subsequently be accessed as fields within the struct.

The only tricky part is that you’ll need to work out where the actual CRC bytes are based on Length and then extract these from the payload[] buffer, but this is not too difficult:

Message msg;

ssize_t n = read(fd, &msg, sizeof(msg));            // read data into `msg`

uint16_t crc = *(int16_t*)&msg.payload[msg.Length]; // extract CRC

// validate CRC + perhaps also verify that n is consistent with msg.Length

// then access elements as needed:

src_id = msg.Src_ID;
dst_id = msg.Dst_ID;

9

solved How to parse received data with variable length