DRINK
DRINK

Reputation: 452

How do I send a UDP packet with an exact size?

I have a simple client/server program in Python, using UDP. I need to send packets with a message of exactly 120 bytes in size plus the header. (Total packet size is 120 + sizeof(header).)

How should I do that? What should the contents of MESSAGE be?

My code:

MESSAGE = "?120B?"

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

Upvotes: 0

Views: 3845

Answers (2)

David Callanan
David Callanan

Reputation: 5800

You can use the ljust method to fill a string to a fixed length:

>>> MESSAGE.ljust(120)
'?120B?                                                                                                                  '

However if the length of the string exceeds 120, ljust won't truncate it. You can do that manually by doing this:

MESSAGE.ljust(120)[:120]

The above example will fill the string with a space by default. You can optionally specify a custom fill character (for example a null character):

MESSAGE.ljust(120, '\0')[:120]

It looks like you want to fill the string with null characters, but remember that the receiver will likely cut the string off when it reaches the first null character if a length is not given. I'm guessing that you plan on storing the length of the string in the header, and if you do that you shouldn't have any problems.

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114088

def sendPacket(data,sock,data_size):
    packets = ["%s"%data[i:i+data_size] for i in range(0,len(data),data_size)]
    packets[-1] = packets[-1] + "\x00"*(len(data)%data_size)
    for p in packets:
        sock.sendto(p,*ADDRINFO)

sendPacket("hello",sock,120)
sendPacket("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",sock,120)

would break any given data into 120byte packets

Upvotes: 3

Related Questions