16

What is the recommended way to "gracefully" close a TCP socket?

I've learned that close()ing before read()ing all the remaining data in my host buffer can cause problems for the remote host (he could lose all the data in his receive buffer that has been acked, but not yet been read by his application). Is that correct?

What would be a good approach to avoid that situation? Is there some way to tell the API that I don't really care about data being lost due to my ignoring any remaining buffered data and closing the socket?

Or do I have to consider the problem at the application protocol level and use some kind of implicit or explicit "end of transmission" signal to let the other party know that it's safe to close a socket for reading?

lxgr
  • 3,719
  • 7
  • 31
  • 46

1 Answers1

26

1) Call shutdown to indicate that you will not write any more data to the socket.

2) Continue to read from the socket until you get either an error or the connection is closed.

3) Now close the socket.

If you don't do this, you may wind up closing the connection while there's still data to be read. This will result in an ungraceful close.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Ok, I'll do that. Out of curiosity: Is it really possible that the data I've sent TO the remote host could be lost by my ignoring the data in my receive buffer, and not just the data sent BY the host because of the abortive close? – lxgr Jan 15 '12 at 20:23
  • 1
    Yes, data you sent *to* the remote host can be lost because the abortive close can occur before the other side reads the data. You don't want to call `close` until you're confident the connection has been shut down. – David Schwartz Jan 15 '12 at 23:11
  • 3
    1) shutdown(sock, 1) , 2) while(read(sock, ...)=0) 3) close(sock) Is that the order? – ernesto Feb 06 '14 at 06:48
  • I forgot to read before terminating the connection. This helped. Thanks :) – Tejas Jadhav Jan 05 '19 at 13:54
  • It is the same for UDP? – Agapito Gallart Bernat Feb 11 '19 at 22:34
  • 1
    @AgapitoGallartiBernat No. With UDP, there is no connection to worry about cleanly shutting down, at least not as far as UDP itself is concerned. – David Schwartz Feb 12 '19 at 00:43
  • So when you shutdown with shutdown(sock, 3), can you still read the remaining unread buffered data from the other peer? And if no, can you do close() right after that shutdown without causing trouble to the other peer reading all data that was sent to him? – Palo Dec 11 '21 at 17:30