read() on a NON-BLOCKING tun/tap file descriptor g

2019-07-20 05:04发布

问题:

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.