Important: Please read the Qt Code of Conduct -

How to handle ill-formed message? (tcp)

  • Hello,

    this is a general question about network programming, not really related to Qt. but my code is indeed in Qt.

    so I'm creating a tcp server/client application. the message format is very simple, it always starts with a size, then followed by the actual message. the server code logic is simple, once it receives a size, it loops till it is sure that the entire message is received by comparing the message size with the received size. then once the message is received completely, it will process the message.

    but this code can be easily fooled by creating an ill-formed message. for example, I can send a message with a very large size followed by an empty message. (similar to the heart-bleed thing of openssl). this will result in a long loop in my server code (if not a dead loop).

    I don't know how to handle this. for example, I could reject a message when I see a very large message size. But how many bytes should I reject? what's worse is that if I reject some bytes incorrectly, all the following well formed messages are impacted.

    what should I do in this case?


  • Lifetime Qt Champion


    I would rather use a more "complex" protocol with e.g. a start and stop sequence that you would check when reading the data. This way you should be able to identify a good from a bad packet. It's not bullet-proof but it might help.

  • The start/message/stop sequence doesn't prevent an invalid sequence from tying up the server. A malicious client that sends an unreasonably high length can just as well omit the stop message.

    The server needs to apply some heuristics to determine when continuing to service a client is unreasonable. Depending on the application, this may be failure to match a known command, a connection longer than some period of time, resource scarcity, or something else.

    If a length is used, don't trust it for anything more than determining when all of the promised data has been delivered. Use the actual length of the buffer for processing.

  • Hii..
    ill-formed message -->which is not well formatted.
    In order to make a Well formatted Message communication i strongly recommend to use XML .

    hope it helps

Log in to reply