2017-07-27 47 views
-3

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

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__)); 

回答

0

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

要设置版本:

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

设置头长度:

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

我假设你想使用从0x0..0x0f要么进入下或进入更高的值myVal轻咬ip_vhl。然后您可以使用以下语句:

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

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