'Python3 : Parsing packet header with struct library
Recently, I've been looking into PyMySql source code. Just to wanna learn what's going on between Mysql server and client under the hood.
And there's this _read_packet method.
def _read_packet(self, packet_type):
packet_header = self._read_bytes(4)
btrl, btrh, packet_number = struct.unpack("<HBB", packet_header)
bytes_to_read = btrl + (btrh << 16)
This basically tells me that
Read first 4 bytes from the server response. (And this 4 bytes are packet header)
b'N\x00\x00\x00'Unpack the packet header with 'one unsigned short(2bytes), two unsigned char(1byte)'
b'N\x00','\x00','\x00'Then you can get the starting point of the payload(
bytes_to_read).
Here's the thing I couldn't understand:
According to this picture, first 4 bytes match to the picture's first row.
and If I put together the result gotten from unpacking,
- btrl = Version, IHL(Header Length), Type of Service(TOS) (First 2 bytes :
unsigned short - btrh = Half of the Total length (the next 1 byte
unsigned char) - packet_number = The other half of the Total length (The last 1 byte
unsinged char)
Is this the right match? I think something is missing and got the wrong matches.
and after I debug the variables: btrl is 78, btrh is 0, packet_number is 0
What does the btrl, btrh stand for?
Lastly, How can "btrl + (btrh << 16)" be the bytes_to_read?
I mean why 16? What happen if the number is 8, 32 or 64?
Can you guys explain this like talking to your nephew? :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

