我可以从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;
指针调整不是很好。有更安全的方法可以进行此操作。
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));