UDP 消息太长 [英] UDP Message too long

查看:28
本文介绍了UDP 消息太长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 UDP 发送数据,但想知道为什么我的系统 (Mac OS X 10.9) 上的最大数据长度限制为 9253 字节.

I'm trying to send data over UDP and wondering why the maximum data length is limited to 9253 bytes on my system (Mac OS X 10.9).

这就是我发送数据的方式(简化):

This is how I send data (simplified):

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 9999
MESSAGE = "A"*9217

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

我得到了错误

Traceback (most recent call last):
  File "Untitled 2.py", line 8, in <module>
    sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
socket.error: [Errno 40] Message too long

实际上,我可以传输的最大字符串长度"是 9216.当我通过

In fact, the maximum "string length" I can transfer is 9216. When I do a byte size check on the client side via

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 9999

self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((UDP_IP, UDP_PORT))
data, addr = self.sock.recvfrom(65535)
print("Received {0} bytes of data.".format(sys.getsizeof(data)))

我明白

Received 9253 bytes of data.

当我发送 9216 字节(这是以字节为单位的字符串长度)时,我不明白为什么它是 9253 字节长.28 个字节是 UDP 报头,但剩下的 9 个字节存储了什么?

I don't understand why it is 9253 bytes long, when I send 9216 bytes (this is the string length in bytes). 28 bytes is the UDP header but what is stored in the remaining 9 bytes?

我的主要问题是:如何发送和接收最大 65535 字节的 UDP 数据包?

And my main problem: how do I send and receive UDP packets up to 65535 bytes?

推荐答案

我遇到了同样的问题,并为您的 [Errno 40] 找到了解决方案.问题不在于 MTU.MTU 是可以发送的 1 个包裹的最大尺寸.对于以太网,此 MTU 为 1500.

I had the same problem and found a solution for your [Errno 40]. The problem lies not in the MTU. The MTU is the maximum size for 1 package that can be sent. For Ethernet this MTU is 1500.

但是,计算机可以将大于 MTU 的 UDP 包分成更小的包.这样你应该能够发送最多 65535 个 udp 包.

However, computers can fragment a UDP-package that is larger than the MTU into packages that are smaller. That way you should be able to send udp-packages up to 65535.

现在我们来解决您的问题.默认情况下,OSX 将最大 UDP 包限制为 9216 字节,不要问我为什么.您可以在终端中使用以下命令更改此值.

Now we come to your problem. By default OSX has limited the maximum UDP-package to be 9216 bytes, don't ask me why. You can alter this value using the following command in the terminal.

    sudo sysctl -w net.inet.udp.maxdgram=65535

此更改不会在重新启动后继续存在.

This change will not survive a reboot.

请注意,如果其中一个片段未到达其客户端,则整个包将被丢弃.这就是为什么将数据报的大小保持在 MTU 之下更为明智的原因.

Beware that if one of the fragments does not reach its client, the whole package is dropped. That is why it is smarter to keep the size of your datagrams under the MTU.

这篇关于UDP 消息太长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆