简体   繁体   中英

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

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?

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.

TCP guarantees order. So I will just assume you are talking about IP.

One thing you could try is putting the packets in a min-heap and then waiting until the next packet ID number you want is available.

As for the push packets, those are supposed to be received as soon as possible without a restriction on ordering, so its up to you to decide how long you want to wait to see if you'll receive an earlier push packet.

为什么不使用普通的tcp套接字以便按顺序排列?

The Sequence number will show the order. It wraps at 4G so you will have to account for that. And you will have to use the same basic routine that TCP uses. Buffer out of order packets and discard duplicates. Sequence Number + Len of payload is the nexxt sequence number.

TCP/IP Illistrated vol 2 or TCP.c ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM