Last active
August 2, 2016 02:50
-
-
Save mydreambei-ai/ce9a02494abd81542791d93538d588aa to your computer and use it in GitHub Desktop.
python reading all the data from a UDP socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import sys | |
''' | |
The correct maximum UDP message size is 65507, | |
as determined by the following formula: 0xffff - (sizeof(IP Header) + sizeof(UDP Header)) = 65535-(20+8) = 65507 | |
http://stackoverflow.com/questions/1098897/what-is-the-largest-safe-udp-packet-size-on-the-internet | |
search gateway MTU: | |
ping -s 1500 -M do <gateway> | |
''' | |
messages = [b'x' * 65507] * 3 | |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
print(s.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)) | |
for data in messages: | |
s.sendto(data, ('127.0.0.1', int(sys.argv[-1]))) | |
print(s.recv(1024)) | |
s.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding=utf8 | |
''' | |
http://stackoverflow.com/questions/11026316/reading-all-the-data-from-a-udp-socket | |
''' | |
import socket | |
import sys | |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
s.bind(('127.0.0.1', int(sys.argv[-1]))) | |
print('Bind UDP on {0}...'.format(int(sys.argv[-1]))) | |
while True: | |
data, address = s.recvfrom(65507) | |
print('Received from', address, len(data)) | |
message = 'Hello {0!r} {1!r} '.format(address, int(sys.argv[-1])) | |
s.sendto(message.encode(), address) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment