Python UDP套接字每65536个数据包就有数据包丢失

时间:2019-01-10 07:41:04

标签: python sockets networking

我正在使用python套接字接收带有自定义帧计数器的FPGA发送的UDP数据包,以指示数据包丢失。我的问题是,每收到65536个数据包,接收到的数据就会丢失4个数据包。 Windows套接字是否有65536个数据包限制? 我无法在自己的帖子中嵌入图片。我将在下面输入运行结果:

start: 395070354
end: 395344794
Number of packets: 274441
Missing 4 packet from: 395115893 to: 395115898 distance from start: 45539
Missing 4 packet from: 395181429 to: 395181434 distance from start: 45539
Missing 4 packet from: 395246965 to: 395246970 distance from start: 45539
Missing 4 packet from: 395312501 to: 395312506 distance from start: 45539
Number of missing packets: 16

从结果中可以看到,这很正常。 395181434-395115898 = 65536。每65536个数据包丢失4个数据包。

我尝试降低传输速度。我认为这可能是缓冲区大小的问题。我使用setsockopt函数来更改RECVBUF的大小,但是它不起作用。

import socket
import time
import threading

def receive():
    global data
    while not kill.is_set():
        data.append(fpga.recvfrom(512)[0])

fpga = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
fpga.bind(('192.168.253.8', 34))
miss=0
data=[]
kill=threading.Event()
p=threading.Thread(target=receive)
p.start()
time.sleep(10)
kill.set()
count=len(data)
start=int.from_bytes(data[0][0:4], byteorder='big')
end=int.from_bytes(data[count-1][0:4], byteorder='big')
print("start: ",start)
print("end: ",end)
print("Number of packets: ",end-start+1)
for i in range(0,count-1):
    current=int.from_bytes(data[i][0:4], byteorder='big')
    next=int.from_bytes(data[i+1][0:4], byteorder='big')
    if next < current:
        print("out of order detected!!!")
        break
    step=next-current
    miss=miss+step-1
    if step > 1:
        print("Missing ",step-1," packet form: ",current," to: ",next,"distance form start: ",current-start)
print("Number of missing packets: ",miss)

1 个答案:

答案 0 :(得分:1)

我怀疑与Windows有什么关系,我希望它故意丢弃数据包,因为它们格式错误/不符合规范(例如,校验和计算错误,这是一个16位数字)

弄清楚发生了什么事,我建议使用数据包嗅探器(例如Wireshark,tcpdump,Scapy)来记录您的Python脚本所看到的相同流量。如果幸运的话,过滤“格式错误”的数据包将发现“丢失”的数据包。否则,您可以尝试在捕获的网络流量中找到数据包,在其中有一个序列号应该使此操作非常容易。您还可以更改Python代码以记录时间戳,这可能有助于缩小范围