开发者

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开发者_StackOverflow社区 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).


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.


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.


man says about recv: the return value will be 0 when the peer has performed an orderly shutdown.

That doesn't apply to UDP. There is no "connection" to shut down in UDP. A return value of 0 is perfectly valid, it just means datagram with no payload was received (i.e. the IP and UDP headers only.)

Not sure that helps your problem or not. I really don't understand where you are going with the len=1 stuff.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜