D
D
duoman2017-01-15 00:48:11
Python
duoman, 2017-01-15 00:48:11

Python parsing tcp packet?

It is necessary to parse the tcp packet bit by bit.
Given 16 bytes of tcp packet. I need to parse it into bytes and bits. I want to use python for this because it is the most familiar to me.
Roughly speaking, the packet is divided into parameters:
1 - byte int number
2 - byte must contain 4 parameters, two bits for each
3 - 6 bytes 32 bit number
, and so on.
To parse the package, I wrote a small code:

f = open('file.bin','rb')
b = f.read()
packet[0] = b[0]
packet[1] = b[1]
packet[2] = struct.unpack('>I',b[2:6])

Then the questions began to how to pull out the bits I needed from b[1].
On the one hand, the task is simple. But due to lack of experience, I do not know how to solve this problem.
Who faced direct me to the correct solution for parsing binary data.
I also don’t know what to use to display data in the binary system on the display. On the Internet, they mostly post examples of working with bytes, but here's how to work with bits ... Maybe I'm not asking the right questions

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
un1t, 2017-01-15
@un1t

Take the value of a byte. It has 8 bits. To find out the value of a bit, you need to use the logical operation &
For example, read the value of the byte into the variable x
x & 1 # value of the first bit
x & 1 << 1 # value of the second bit
x & 1 << 2 # value of the third bit
operation << is a bitwise shift
googled something like "python bit operations"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question