Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discard incoming UDP packet without reading

In some cases, I'd like to explicitly discard packets waiting on the socket with as little overhead as possible. It seems there's no explicit "drop udp buffer" system call, but maybe I'm wrong?

The next best way would be probably to recv the packet to a temporary buffer and just drop it. It seems I can't receive 0 bytes, since man says about recv: The return value will be 0 when the peer has performed an orderly shutdown. So 1 is the minimum in this case.

Is there any other way to handle this?

Just in case - this is not a premature optimisation. The only thing this server is doing is forwarding / dispatching the UDP packets in a specific way - although recv with len=1 won't kill me, I'd rather just discard the whole queue in one go with some more specific function (hopefully lowering the latency).

like image 746
viraptor Avatar asked Jun 21 '10 15:06

viraptor


2 Answers

You can have the kernel discard your UDP packets by setting the UDP receive buffer to 0.

int UdpBufSize = 0;
socklen_t optlen = sizeof(UdpBufSize);
setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &UdpBufSize, optlen);

Whenever you see fit to receive packets, you can then set the buffer to, for example, 4096 bytes.

like image 123
WindsurferOak Avatar answered Oct 05 '22 14:10

WindsurferOak


I'd rather just discard the whole queue in one go

Since this is UDP we are talking here: close(udp_server_socket) and socket()/bind() again?

To my understanding should work.

like image 44
Dummy00001 Avatar answered Oct 05 '22 14:10

Dummy00001