用C中的char *有效负载构造struct

时间:2020-03-19 10:05:23

标签: c memory struct char ethernet

我可以从char *有效负载填充结构的所有字段吗?

例如,如果我的结构是:

    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 :(得分:0)

指针修剪不是一件好事。有更安全的方法可以做到这一点。

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));
相关问题