在C中解析SIP数据包

kam*_*one 5 c parsing sip

我正在尝试解析SIP数据包并从中获取一些信息.更具体地说,数据包看起来像这样

REGISTER sip:open-ims.test SIP/2.0
Via: SIP/2.0/UDP 192.168.1.64:5060;rport;branch=z9hG4bK1489975971
From: <sip:alice@open-ims.test>;tag=1627897650
To: <sip:alice@open-ims.test>
Call-ID: 1097412971
CSeq: 1 REGISTER
Contact: <sip:alice@192.168.1.64:5060;line=5fc3b39f127158d>;+sip.instance="<urn:uuid:46f525fe-3f60-11e0-bec1-d965d1488cfa>"
Authorization: Digest username="alice@open-ims.test", realm="open-ims.test", nonce=" ", uri="sip:open-ims.test", response=" "
Max-Forwards: 70
User-Agent: UCT IMS Client
Expires: 600000
Supported: path
Supported: gruu
Content-Length: 0
Run Code Online (Sandbox Code Playgroud)

现在,从该数据包我需要提取以下内容:

  • "From:"之后的值(在本例中<sip:alice@open-ims.test>)
  • "联系人:"之后的值(在这种情况下<sip:alice@192.168.1.64)
  • "用户名"后面的值(在本例中alice@open-ims.test)

到目前为止我的代码是这样的

char * tch;
      char * saved;                    
      tch = strtok (payload,"<>;");
      while (tch != NULL)
      { 
        int savenext = 0;              
        if (!strcmp(tch, "From: "))     
        {                              
          savenext = 1;                
        }                              

        tch = strtok (NULL, "<>;");
        if (savenext == 1)             
        {                              
          saved = tch;                 
        }                              
      }
      printf ("### SIP Contact: %s ###\n", saved);  
        }
    }
Run Code Online (Sandbox Code Playgroud)

其中有效载荷包含如上所述的分组.

但是,当我运行我的程序时,它将导致分段错误.奇怪的是,如果我在strtok中使用字符"<>;:"并在strcmp中使用值"sip"消息将成功解析并保留保存的值.但我需要解析所有三个上限值.

请问一个sip库可以帮助我解决我的问题吗?

提前致谢

小智 4

我认为这样的事情可以工作

char * tch;
        char * saved;                    
        tch = strtok (payload,"<>;\n\"");
        while (tch != NULL)
        { 
            int savenext = 0;              
            if (strncmp(tch, "From",4)==0)   
            {                                 
            tch = strtok (NULL, "<>;\n\"");
            saved = tch;                 
            printf ("   SIP From: %s \n", saved); 
            }   
            else if (strncmp(tch, "Contact",7)==0) 
            {                                 
            tch = strtok (NULL, "<>;\n\"");
            saved = tch;                 
            printf ("   SIP Cont: %s \n", saved); 
            } 
            if (strncmp(tch, "Authorization",13)==0)  
            {                                     
            tch = strtok (NULL, "<>;\n\"");
            saved = tch;                 
            printf ("   SIP User: %s \n", saved); 
Run Code Online (Sandbox Code Playgroud)