http://www.perlmonks.org?node_id=18688


in reply to Deteriming how much is left to read on a filehandle

I've wondered the same thing. First, for filehandles, I know you can use -s HANDLE to return the size of the file. If you use the read to read from the file, it will return the number of bytes read, and you can subtract that from another variable you initially set to the file size. Unfortunately, this (as far as I know) only works for files.

I've tried something similar on sockets and -s just doesn't return anything unless there's data. If there isn't any, it waits until there is, which could be never. So, to conditionally read from the socket if there was any data on it, I installed an SIGALRM handler to timeout any read operations after 1 second. Of course if I didn't want it to pause that would just totally suck. Anyway, I'm rambling, but I know of no way to check how much data is waiting on a socket. Still, read does return how much data was read from a socket, but someone please correct me if I'm wrong, it will continue to read, or try to read, until it reads either an EOF or however many bytes you tell it to read. Plus you have no way of knowing how many bytes are waiting to be read in the first place, and thus no way to know how much is left.

I'm going to vote up your node because I really really want an answer to this myself, and for some reason it hasn't landed on the SOPW page yet.

72656B636148206C72655020726568746F6E41207473754A