Linux – How to discard incoming packets in raw socket


I'm writing a C/C++ application under Linux that reads data from a raw socket (for ICMP packets). Question: is there a way to discard all data that is still queued on the socket?

The problem is that after sleeping for a while, there is data queued up on the socket which I'm not interested in; so it would be best to just tell the socket "forget all data you have buffered right now", so that if I go into a select()/recvfrom() loop then, I only get data that was received recently.

Is there a better way than going into a separate poll()/recvfrom() loop first? Some socket API call maybe? Portable, even? 🙂

Best Solution

During idle times, you can disable the socket by setting the Receive Buffer size to zero:

 int optval = 0; /* May need to be 1 on some platforms */

 setsockopt(sockDesc, SOL_SOCKET, SO_RCVBUF, (char *)(&optval), sizeof(optval));

Re-enable by setting "optval" to a larger buffer (e.g. 4096).