Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding packed data into a structure

What would the best way of unpacking a python string into fields

I have data received from a tcp socket, it is packed as follows, I believe it will be in a string from the socket recv function

It has the following format

uint8 - header
uint8 - length
uint32 - typeID
uint16 -param1
uint16 -param2
uint16 -param3
uint16 -param4
char[24] - name string
uint32 - checksum
uint8 - footer

(I also need to unpack other packets with different formats to the above)

How do I unpack these?

I am new to python, have done a bit of 'C'. If I was using 'C' I would probably use a structure, would this be the way to go with Python?

Regards

X

like image 304
mikip Avatar asked Dec 08 '22 05:12

mikip


2 Answers

The struct module is designed to unpack heterogeneous data to a tuple based on a format string. It makes more sense to unpack the whole struct at once rather than trying to pull out one field at a time. Here is an example:

fields = struct.unpack('!BBI4H20sIB', data)

Then you can access a given field, for example the first field:

fields[0]

You could also use the tuple to initialize a NamedTuple; look at the documentation for struct for an example. NamedTuples are only available in Python 2.6+, but they behave more like Python structures in that you can access elements as attributes, e.g. fields.header. Of course, you could also accomplish this with a little more work by writing a class to encapsulate the information from the tuple... again, if you care. You can always just index into fields directly, as I showed above.

like image 162
musicinmybrain Avatar answered Jan 01 '23 21:01

musicinmybrain


use struct module

like image 30
SilentGhost Avatar answered Jan 01 '23 22:01

SilentGhost