python - 提取一些 SIP header

标签 python python-2.7 sip

我使用 SIP(​​ session 启动协议(protocol))URI 的正则表达式来提取不同的内部变量。

_syntax = re.compile('^(?P<scheme>[a-zA-Z][a-zA-Z0-9\+\-\.]*):'  # scheme
    + '(?:(?:(?P<user>[a-zA-Z0-9\-\_\.\!\~\*\'\(\)&=\+\$,;\?\/\%]+)' # user
    + '(?::(?P<password>[^:@;\?]+))?)@)?' # password
    + '(?:(?:(?P<host>[^;\?:]*)(?::(?P<port>[\d]+))?))'  # host, port
    + '(?:;(?P<params>[^\?]*))?' # parameters
    + '(?:\?(?P<headers>.*))?$') # headers
m = URI._syntax.match(value)
    if m: 
        self.scheme, self.user, self.password, self.host, self.port, params, headers = m.groups()

我想提取特定的 header ,例如via、branch、contact、callID或Cseq的 header 。 sip消息的一般形式为:

OPTIONS sip:172.16.18.35:5060 SIP/2.0
Content-Length: 0
Via: SIP/2.0/UDP 172.16.18.90:5060
From: "fake" <sip:fake@172.16.18.90>
Supported: replaces, timer
User-Agent: SIPPing
To: <sip:172.16.18.35:5060>
Contact: <sip:fake@172.16.18.90:5060>
CSeq: 1 OPTIONS
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH
Call-ID: fake-id@172.16.18.90
Date: Thu, 25 Apr 2013 003024 +0000
Max-Forwards: 70

最佳答案

我建议利用 SIP header 格式和 RFC822 之间有意的相似性。

from email.parser import Parser
msg = Parser().parsestr(m.group('headers'))

...此后:

>>> msg.keys()
['Content-Length', 'Via', 'From', 'Supported', 'User-Agent', 'To', 'Contact', 'CSeq', 'Allow', 'Call-ID', 'Date', 'Max-Forwards']
>>> msg['To']
'<sip:172.16.18.35:5060>'
>>> msg['Date']
'Thu, 25 Apr 2013 003024 +0000'

...等等。请参阅 the Python standard-library email module 的文档了解更多详情。

关于python - 提取一些 SIP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37472560/

相关文章:

python - vertica-python 复制本地时出错

python - pip安装模块错误

ios - 我们可以在 SIP Voip 应用程序中使用 PJSIP/Siphon

python - 使用 BeautifulSoup 查找具有两种特定样式的标签

android - Samsung Galaxy SII 密码错误问题

ubuntu - 如何在 ubuntu 16.04 上安装 Jitsi SIP 电话

python - pandas 中的高效扩展 OLS

python - 循环遍历列并在特定条件下停止(python)

python - if elif 语句中的表达式评估

python - 如何以有效的方式将具有 MultiIndex 的数据帧合并到另一个数据帧中?