C#: How to deal with out-of-order TCP packets

c++sockets

Can please someone one explain how to deal with out-of-order packets. I'm using raw socket to capture packets, and parse them as they come, but some of them come in wrong order, for example:

  1. Id………..Flags
  2. 16390 : (PSH, ACK)
  3. 16535 : (PSH, ACK)
  4. 16638 : (ACK)
  5. 16640 : (PSH, ACK)
  6. 16639 : (ACK)
  7. 16695 : (PSH, ACK)

Packets with IDs: 16390, 16535, 16695 are separate packets and can be processed freely
Packets with IDs: 16638, 16640, 16639 are a sequence of packets and should be put in ascending order before parsing.

To make it worse packets with Push flag sometimes come first so I just pass them along to parser, and then packet that preceds it comes and parser just discards it as corrupted.

Is there any way to deal with it?

Best Solution

TCP segments will not be out of order because the next one will not be sent until you ACK the previous one.

TCP numbers the segments that it sends to a particular destination port sequentially, so that if they arrive out of order, the TCP entity can reorder them.

This happens on a transport layer below TCP so any TCP connections would never "see" this happen. In terms of TCP they are always in order. So if you see them out of order then you are not working on the TCP transport layer, you're at a lower level.

Also, FYI...

  • TCP data is a "segment"
  • IP data is a "datagram"
  • Network-level is a "packet"

Edit: The link you provided will provide you with a stream of IP datagrams so you would have to handle the TCP stream on your own. I'm not going to pretend like it's easy and try to explain that here.

Related Question