lwip通过结构体解析数据,通讯原始数据与结构体

涉及数据格式

下面一段代码在ip4.h

PACK_STRUCT_BEGIN
/* The IPv4 header */
struct ip_hdr {
  /* version / header length */
  PACK_STRUCT_FLD_8(u8_t _v_hl);
  /* type of service */
  PACK_STRUCT_FLD_8(u8_t _tos);
  /* total length */
  PACK_STRUCT_FIELD(u16_t _len);
  /* identification */
  PACK_STRUCT_FIELD(u16_t _id);
  /* fragment offset field */
  PACK_STRUCT_FIELD(u16_t _offset);
#define IP_RF 0x8000U        /* reserved fragment flag */
#define IP_DF 0x4000U        /* don't fragment flag */
#define IP_MF 0x2000U        /* more fragments flag */
#define IP_OFFMASK 0x1fffU   /* mask for fragmenting bits */
  /* time to live */
  PACK_STRUCT_FLD_8(u8_t _ttl);
  /* protocol*/
  PACK_STRUCT_FLD_8(u8_t _proto);
  /* checksum */
  PACK_STRUCT_FIELD(u16_t _chksum);
  /* source and destination IP addresses */
  PACK_STRUCT_FLD_S(ip4_addr_p_t src);
  PACK_STRUCT_FLD_S(ip4_addr_p_t dest);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END

struct udp_hdr {
  PACK_STRUCT_FIELD(u16_t src);
  PACK_STRUCT_FIELD(u16_t dest);  /* src/dest UDP ports */
  PACK_STRUCT_FIELD(u16_t len);
  PACK_STRUCT_FIELD(u16_t chksum);
} PACK_STRUCT_STRUCT;


//用到的定义
#define PACK_STRUCT_FLD_8(x) PACK_STRUCT_FIELD(x)
#define PACK_STRUCT_FIELD(x) x
//与udp数据对接
udphdr = (struct udp_hdr *)p->payload;
err_t
ip4_input(struct pbuf *p, struct netif *inp)
{
  struct ip_hdr *iphdr;

  /* identify the IP header */
  iphdr = (struct ip_hdr *)p->payload;
  ...

PACK_STRUCT_STRUCT attribute ((packed))

串口数据传输数据时,共用体和结构体如何转换
实际使用时,会出现问题,可以参考LWIP修改

struct data_m
{
    char add;
    short code;
    char end;
};

int main()
{
    struct data_m *st;
    st = data;
    printf("add:%x,code:%x,end:%x",st->add,st->code,st->end);
    
    return 0;
}

由于字节对齐,实际结果会是这样:add:12,code:7856,end:2

你可能感兴趣的:(嵌入式)