How to ensure my udp sockets receive all packets in order? Assuming the packets are guarantee arrive in order at the receiver machine, and no packet drop.
I am asking this because I ran my program many times in window, and redhat. It always receive in-order packets under windows, on the other hand, out-of-order packet always happen under redhat as well as ubuntu.
I am using boost asio library to create 50 udp sockets, receive rate set to 100 packet/sec. I also have tried without boost asio, and use a boost thread to listen to an epoll, and call recv to fd immediately, but yielded the same result. In addition, If I only open 8 sockets in linux, i receive no out-of-order packets.
UDP does not guarantee that packets are received in order, or even received at all: User Datagram Protocol - Wikipedia, the free encyclopedia
So to guarantee this you will either have to implement it yourself, or use TCP.
Or use SCTP, which preserves both message boundaries (which TCP does not) and message order (which UDP does not).
Even with those assumptions in place, UDP packets logically have no relation to each other, so the kernel doesn't have to make any special effort to ensure they are seen by the application in the same order they are seen by the network interface. You'd think that would be the case, but there are all sorts of reasons why it might not be. For instance, the packets might be queued in a LIFO fashion instead of a FIFO, simply because that was easier to implement and permitted to do.
Originally Posted by Bryan Fok
You're relying on undefined behavior by relying on the order of UDP packets.
If they must be in order then attach a value that indicates the number of the packet in the sequence and re-order them yourself when they're received. Also, instead of assuming that packets won't be dropped, decide whether you can afford to drop them, and if you can't, send something back indicating that the other side successfully received the packet, and keep sending the same data until that is received. You can safely fit around 512 bytes into a UDP datagram, so keep that in mind when you're designing your protocol.
or use Reliable Datagram Sockets, although it's unclear to me whether it enforces packet ordering.