1

I am trying to read a file from a socket. I use select with timeout to exit after reading.

select(maxfdp1, &rset, NULL, NULL, &timeout);

But if I knew the size of the file being sent right away, I could exit instantly after getting the right amount of bytes.

Сan i get the full file size before transferring it?

Or what should I use to exit instantly after the transfer is complete?

Daniel Walker
  • 5,220
  • 3
  • 18
  • 39
AlanSan
  • 19
  • 2
  • You may find this helpful: https://stackoverflow.com/questions/14047802/how-to-check-amount-of-data-available-for-a-socket-in-c-and-linux – Daniel Walker May 19 '20 at 18:39
  • 1
    Even the delay of TCP FIN from server to client is intolerable ? – m0hithreddy May 19 '20 at 18:43
  • 1
    I think the question here and the link you posted is completely unrelated... Just reading the size of current socket buffer gives no details about the file size. Even if it is one byte that is remaining to read, we wont get an EOF until the next call (assuming server FIN already reached client) – m0hithreddy May 19 '20 at 18:52
  • @MohithReddy *Even the delay of TCP FIN from server to client is intolerable ? Fin delay is ok – AlanSan May 20 '20 at 20:09
  • @AlanSan In that case, just close the socket from server side just after writing the file to the socket, client automatically gets an EOF and you can terminate after getting an EOF – m0hithreddy May 20 '20 at 20:24

1 Answers1

3

Because TCP is a stream-oriented protocol, it has no concept of the size of an application layer message. If you're setting up your own application layer protocol on top of the TCP, you could have your sender first transmit the size of the following data, such as four bytes in network order (big Endian).

Once you've received all of the data you want, you can call close on the socket.

Daniel Walker
  • 5,220
  • 3
  • 18
  • 39