从C中的char *有效载荷构造结构

问题描述 投票:0回答:1

我可以从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;
c memory struct char ethernet
1个回答
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));
© www.soinside.com 2019 - 2024. All rights reserved.