c语言解析协议常用套路

简介

协议定义username,len,value;
while 读取;
2个switch,case解析.读取value.

代码示例

struct stun_attr {//每种协议都是username,len,value
    unsigned short attr; //username
    unsigned short len;  //len  
    unsigned char value[0];  //根据len直接分配,不需要向value*一样手动在分配一次.
} __attribute__((packed));

//太经典了,嵌入式,不用深拷贝。使用
struct stun_attr *stunmsg;
struct stun_attr *attr;
data = buf + sizeof(struct stun_header);
    
switch (ntohs(hdr->msgtype)) 
{
  while(len) 
  {
       attr = (struct stun_attr*)data;  //太经典了,直接根据           
       switch (ntohs(attr->attr)) {//转发stun request
       case STUN_XOR_MAPPED_ADDRESS:
       { 
          struct stun_addr* aa =(struct stun_addr*)attr->value;
       }
       break;
    }         
    data += ntohs(attr->len) + sizeof(struct stun_attr);
    len -= ntohs(attr->len) + sizeof(struct stun_attr);
} 

你可能感兴趣的:(通讯协议,c语言,开发语言)