Unpacking bytes with struct module


I’m using socket module to capture packets on a TCP port, and store it in a file called output.txt, as seen in the code below.
I want to use struct to convert the bytes to a human-readable format but I am unable to do so, as struct expects me to know the length and type of the bytes, which is unknown to me.
How can I utilise struct to unpack unknown TCP packets?


>>> with open('output.txt', 'rb') as f:
...     data = f.read()
>>> print(data)

I’ve not tried reading TCP packets but I think it’s the same problem, apologies if that’s not the case. If you don’t know what it is then how would struct know either? It’s not a tool used for dealing with unknown data dumps. If I’m not mistaken there’s software for precisely this sort of thing that would likely be worth looking into.

The closest I’ve come was having to unpack a series of binary files since no-one had the original software. It took a lot of trial and error. It was only possible (within a sensible time-frame) as I knew portions of the unpacked contents and there were markers in the code (the proper name escapes me) providing the length and type of the following x bytes. If neither of those things are available then either save an output and spend a nightmarish amount of time guessing types and lengths until you work out the format yourself or avoid reinventing the wheel and have a look for software already designed for this sort of thing. Without some basis for the structure of the data I can see this being an unreasonable amount of work for you.