gpt4 book ai didi

python - Python 中的分段 TCP 消息

转载 作者:可可西里 更新时间:2023-11-01 02:49:15 24 4
gpt4 key购买 nike

我有一个应用程序可以实时读取实时 SIP 数据包和解码信息。当数据包较小时,UDP/TCP 能够获取信息,但当数据包较大时,它到达不同的段:以下是 Wireshark 的摘录:

3 Reassembled TCP Segments (3331 bytes): #1(1448), #3(1448), #5(435)
Frame: 1, payload: 0-1447 (1448 bytes)
Frame: 3, payload: 1448-2895 (1448 bytes)
Frame: 5, payload: 2896-3330 (435 bytes)
Segment count: 3
Reassembled TCP length: 3331

我的应用程序认为每个片段都有一个新的 SIP 数据包并且无法解码信息。我怎样才能做到这一点?我需要读取数据包,如果碎片化,则组装所有 sip 消息并将信息传递到我的控制模块。这是我当前的代码:

s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))

while (True):
packet = s.recvfrom(65565)
#packet string from tuple
packet = packet[0]
#parse ethernet header
eth_length = 14

eth_header = packet[:eth_length]
eth = unpack('!6s6sH' , eth_header)
eth_protocol = socket.ntohs(eth[2])


if eth_protocol == 8 :
#Parse IP header
#take first 20 characters for the ip header
ip_header = packet[eth_length:20+eth_length]

#now unpack them :)
iph = unpack('!BBHHHBBH4s4s' , ip_header)

version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF

iph_length = ihl * 4

ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8]);
d_addr = socket.inet_ntoa(iph[9]);


#TCP protocol

if protocol == 6 :
t = iph_length + eth_length
tcp_header = packet[t:t+20]

#now unpack them :)
tcph = unpack('!HHLLBBHHH' , tcp_header)

source_port = tcph[0]
dest_port = tcph[1]
sequence = tcph[2]
acknowledgement = tcph[3]
doff_reserved = tcph[4]
tcph_length = doff_reserved >> 4

if dest_port == sipLocatorConfig.SIP_PORT:
print
logging.info("------------------------------------------------------SIP Packet detected------------------------------------------------------")
h_size = eth_length + iph_length + tcph_length * 4
data_size = len(packet) - h_size
#get data from the packet
data = packet[h_size:]

ipInfo = {}
ipInfo['protocol'] = protocol
ipInfo['s_addr'] = str(s_addr)
ipInfo['source_port'] = source_port
ipInfo['d_addr'] = str(d_addr)
ipInfo['dest_port'] = dest_port
processSipPacket(data,ipInfo)

最佳答案

我相信这就是我编写 bufsock 的目的: http://stromberg.dnsalias.org/~strombrg/bufsock.html

它允许你说“给我所有数据直到下一个空值”或“给我下一个 64 字节”和类似的话。它智能地处理碎片化和聚合的数据包。

与许多此类工具不同,它不需要您在生产者和消费者端都拥有 bufsock - 您可以在一端使用它而不是另一端。它有点像 python 中用于套接字的 stdio。

它适用于 CPython 2.x、CPython 3.x、Pypy、Pypy3(目前仍处于测试阶段)和 Jython。

关于python - Python 中的分段 TCP 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19761294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com