Dumb and obvious thoughts about parsing binary protocols

6 thoughts
last posted May 14, 2014, 6:42 a.m.

5 earlier thoughts

0

Lesson 3

Remember to implement the checksums (if there are some)! This will help in the following cases:

  • your protocol doesn't have a clearly defined end-of-message marker
  • chances are that your message might also have the header in the payload data, in which case our aforementioned findData && badMessage structure would break down

For either of these cases, you could attempt a parse and know whether you have a valid message or not. This would then roughly become like so:

def validate(data):
    messageOffsets = findMessages(data)
    if messageOffsets[1] < messageLength:
        try:
            parseMessage(data[:messageLength])
            return data[:messageLength]
        except badDecode:
            return failure
    else:
        """ validation here """
        if data[0:4] == '\x01\x02\x03\x04':
            return data[:messageLength]