read() on a NON-BLOCKING tun/tap file descriptor gets EAGAIN error

江枫思渺然 提交于 2019-12-12 21:05:32

问题


I want to read IP packets from a non-blocking tun/tap file descriptor tunfd I set the tunfd as non-blocking and register a READ_EV event for it in libevent.

when the event is triggered, I read the first 20 bytes first to get the IP header, and then read the rest.

nr_bytes = read(tunfd, buf, 20);
...
ip_len = .... // here I get the IP length
....
nr_bytes = read(tunfd, buf+20, ip_len-20);

but for the read(tunfd, buf+20, ip_len-20) I got EAGAIN error, actually there should be a full packet, so there should be some bytes, why I get such an error?

tunfd is not compatible with non-blocking mode or libevent?

thanks!


回答1:


Reads and writes with TUN/TAP, much like reads and writes on datagram sockets, must be for complete packets. If you read into a buffer that is too small to fit a full packet, the buffer will be filled up and the rest of the packet will be discarded. For writes, if you write a partial packet, the driver will think it's a full packet and deliver the truncated packet through the tunnel device.

Therefore, when you read a TUN/TAP device, you must supply a buffer that is at least as large as the configured MTU on the tun or tap interface.



来源:https://stackoverflow.com/questions/17138626/read-on-a-non-blocking-tun-tap-file-descriptor-gets-eagain-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!