pythonsocketsencodingpacked

Python Sockets send Uint16 and Uint32


I need to send a request via a python socket with the following structure:

{
   Uint16 data_one
   Uint16 data_one
   Uint32 data_one
}

I have my server and client working, but i do not really know how can i encode and decode this kind of data to send it over the socket. Thanks!


Solution

  • Take a look at the functions in the struct module. Use struct.pack to generate the bytestream and send it over the wire, then use struct.unpack on the other end to unpack the data:

    # sender
    buffer = struct.pack('!3H', *data)
    # ... send it
    
    
    # receiver
    # ... get the buffer
    data = struct.unpack('!3H', buffer)