Построение структуры из char * payload в C - PullRequest
0 голосов
/ 19 марта 2020

Могу ли я заполнить все поля структуры из char * payload?

Например, если моя структура:

    struct  ether_header {
        u_char  ether_dhost[6];
        u_char  ether_shost[6];
        u_short ether_type;
    };

Как я могу построить свою

char payload[MAXLEN];

так как

// equivalent to assigning "abcde" to eth_hdr->shost, eth_hdr->dhost
// and any dummy numeric value to eth_hdr->ether_type*
struct ether_header *eth_hdr = (struct ether_header *) payload;

1 Ответ

0 голосов
/ 19 марта 2020

Наказание указателя - это не то, что хорошо. Есть более безопасные способы сделать это.

memcpy(&ourstruct, payload, sizeof(ourstruct));

или

union 
{
     struct  ether_header str;
     char payload[MAXLEN];
}myunion;

или просто скопировать поля, если позиции не совпадают

memcpy(ourstruct.ether_dhost[0], &payload[ether_dhost_POS], sizeof(ourstruct.ether_dhost));
...