Reputation: 26259
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))
and I got the error
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
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)))
I get
Received 9253 bytes of data.
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?
And my main problem: how do I send and receive UDP packets up to 65535 bytes?
Upvotes: 18
Views: 26599
Reputation: 1327
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.
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.
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.
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.
Upvotes: 34
Reputation: 3159
65535 bytes is quite a long dataframe, almost no network cards support it. MTU of slightly more that 9k bytes is standard for most Gigabit Ethernet NICs now.
Possible reasons why additional bytes appear:
1) zero padding that the network card may add to the end of the packet
2) It counts L2 header
You can install Wireshark and see exactly what you send and receive. Using this tool is a good way to understand what is the problem
Upvotes: 4