使用定义 (C) 写入结构偏移量



我有一个结构,我可以使用IP_V(ip)IP_HL(ip)两个定义来读取,但我也需要写入它们。在给定结构struct pkt_ip ip;ip_vhl写入较低位和较高位的语法是什么?

struct pkt_ip
{
uint8_t         ip_vhl;         /* header length, version */
#define IP_V(ip)        (((ip)->ip_vhl & 0xf0) >> 4)
#define IP_HL(ip)       ((ip)->ip_vhl & 0x0f)
uint8_t         ip_tos;         /* type of service */
#define IP_DSCP(ip)        (((ip)->ip_tos & 0xfc) >> 4)
#define IP_ECN(ip)       ((ip)->ip_tos & 0x3f)
uint16_t        ip_len;         /* total length */
uint16_t        ip_id;          /* identification */
uint16_t        ip_off;         /* fragment offset field */
#define IP_DF 0x4000                    /* dont fragment flag */
#define IP_MF 0x2000                    /* more fragments flag */
#define IP_OFFMASK 0x1fff               /* mask for fragmenting bits */
uint8_t         ip_ttl;         /* time to live */
uint8_t         ip_p;           /* protocol */
uint16_t        ip_sum;         /* checksum */
struct  in_addr ip_src,ip_dst;  /* source and dest address */
} __attribute__ ((__packed__));

您需要自己在ip_vhl字段上进行位操作。

要设置版本:

header.ip_vhl = (header.ip_vhl & 0x0f) | ((new_version & 0xf) << 4);

要设置标头长度:

header.ip_vhl = (header.ip_vhl & 0xf0) | (new_length & 0xf);

我假设你想使用一个值myVal范围从0x0..0x0f到较低的或较高的ip_vhl。然后,您可以使用以下语句:

ip_vhl = (ip_vhl & 0x0f) | ((myVal & 0x0f) << 4)
ip_vhl = (ip_vhl & 0xf0) | (myVal & 0x0f)

最新更新