Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to detect wrap-around in a fixed-width message counter?

I'm writing a client application to communicate with a server program via UDP. The client periodically makes requests for data and needs to use the most recent server response. The request message has a 16-bit unsigned counter field that is echoed by the server so I can pair requests with server responses.

Since it's UDP, I have to handle the case where server responses arrive out of order (or don't arrive at all). Naively, that means holding on to the highest message counter seen so far and dropping any incoming message with a lower number. But that will fail as soon as we pass 65535 messages and the counter wraps back to zero. Is there a good way to detect (with reasonable probability) that, for example, message 5 actually comes after message 65,000?

The implementation language is C++.

like image 666
Michael Kristofik Avatar asked Dec 22 '25 01:12

Michael Kristofik


1 Answers

The usual way to handle this is do to a modulo subtraction. Sequence number b is after sequence number a if & only if (a - b) % 65536 is greater than (b - a) % 65536.

For your example, (65000 - 5) % 65536 is 64995 and (5 - 65000) % 65536 is 541, so sequence number 5 is after sequence number 65000.

like image 192
caf Avatar answered Dec 24 '25 18:12

caf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!