Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 212
misteryes Avatar asked Dec 05 '25 06:12

misteryes


1 Answers

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.

like image 93
Celada Avatar answered Dec 08 '25 02:12

Celada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!