36

Is it wise/safe to close() a socket directly after the last send()?

I know that TCP is supposed to try to deliver all remaining data in the send buffer even after closing the socket, but can I really count on that?

I'm making sure that there is no remaining data in my receive buffer so that no RST will be sent following my close.


In my case, the close is actually the very last statement of code before calling exit().

Will the TCP stack really continue to try and transmit the data even after the process sending it has terminated? Is that as reliable as waiting for an arbitrary timeout myself before calling close() by setting SO_LINGER?

That is, do the same TCP timeouts apply, or are they shorter? With a big send buffer and a slow connection, the time to actually transfer all the buffered data could be substantial, after all.


I'm not interested at all in being notified of the last byte sent; I just want them to eventually arrive at the remote host as reliably as possible.

Application layer acknowledgements are not an option (the protocol is HTTP, and I'm writing a small server).

4
  • It depends upon the implementation, but in general, yes, a close() will flush any data remaining in the buffer before it actually tears down the socket. Mileage may vary if you terminate the entire process in addition to calling close().
    – aroth
    Commented Jan 15, 2012 at 22:48
  • 3
    @aroth Mileage will not vary if you exit the process. There is no difference between the two cases. If you want to maintain the contrary please provide an authoritative reference.
    – user207421
    Commented Mar 9, 2013 at 4:16
  • @EJP - An authoritative reference on what might happen in arbitrary programs? I don't think such a thing exists. But it's simple enough to posit a plausible example. Say you've got a program that delegates all network operations to a separate thread, like most programs should. It's possible for the main thread to terminate the process (gracefully or otherwise) while the background thread is calling close(). Will the call succeed in that case? I doubt it. Granted, what you say should hold true for any single-threaded program. But not all programs are single-threaded.
    – aroth
    Commented Mar 9, 2013 at 7:23
  • 3
    @aroth No, an authoritative reference that says what you said about 'mileage may vary'. You won't find one. A socket close is a socket close whether it's done by the application or by the kernel when the application exits. Again if you have a counterexample please provide it.
    – user207421
    Commented Mar 27, 2013 at 6:19

4 Answers 4

32

I've been reading the The ultimate SO_LINGER page, or: why is my tcp not reliable blog post a lot. I recommend you read it too. It discusses edge cases of large data transfers with regards to TCP sockets.

I'm not the expert at SO_LINGER, but on my server code (still in active development) I do the following:

  1. After the last byte is sent via send(), I call shutdown(sock, SHUT_WR) to trigger a FIN to be sent.

  2. Then wait for a subsequent recv() call on that socket to return 0 (or recv returns -1 and errno is anything other that EAGAIN/EWOULDBLOCK).

  3. Then the server does a close() on the socket.

The assumption is that the client will close his socket first after it has received all the bytes of the response.

But I do have a timeout enforced between the final send() and when recv() indicates EOF. If the client never closes his end of the connection, the server will give up waiting and close the connection anyway. I'm at 45-90 seconds for this timeout.

All of my sockets are non-blocking and I use poll/epoll to be notified of connection events as a hint to see if it's time to try calling recv() or send() again.

7
  • 3
    That seems like a very good solution as long as the client closes the socket first. However, couldn't he possibly write-close his half of the connection immediately after sending the request? The HTTP spec doesn't say anything on the matter of half-closes; do you think that behavior ever occurs in HTTP clients?
    – lxgr
    Commented Jan 16, 2012 at 8:36
  • No. I did some ad-hoc wireshark sniffs to validate. I encourage you to do the same. From my packet sniffing test - sometimes server sends its FIN after the response and client sends FIN after receiving the response. But most http clients specify the "keep-alive" option with the server anyway, so clients don't initiate a close anyway. In other words, I think it is very safe to assume that clients won't do a half-close.
    – selbie
    Commented Jan 16, 2012 at 11:11
  • Also, clients are likely paying attention to the Content-Length header. It may be plausible that the server doesn't need to do a close or shutdown after sending all his bytes, because the client knows how many bytes to expect in the HTTP resposne. (And the server definitely won't close if it supports connection keep-alive and if the client requested it). But in simpler requests without keep-alive, the server sends a FIN after his response has been sent.
    – selbie
    Commented Jan 16, 2012 at 11:12
  • Ok, so I'll just go with the method described on that very nice linger page, thanks for that link! Seems like any client doing a half-close would have to live with the consequences. I've also never seen a client doing that, but places like docs.python.org/howto/sockets.html specifically suggest a half-close as an effective way to do HTTP(-like protocols), so I thought that behavior was fairly common.
    – lxgr
    Commented Jan 16, 2012 at 11:42
  • I've tried it, and it works regardless of the client sending the FIN immediately after the request or not until after a completed transfer. (In the first case, the process will terminate before finishing the transfer, but the TCP stack will finish the transmission for the now orphaned socket. This might be subject to some timeout, but in my experiment, it kept alive for more than 10 minutes.)
    – lxgr
    Commented Jan 16, 2012 at 15:45
0

Application layer acknowledgements are not an option (the protocol is HTTP, and I'm writing a small server).

HTTP protocol doesn't suffer from this problem. A HTTP server is not supposed to close the connection in any normal operation. The client closes it after recv(), and it knows exactly how many bytes it expects.

And just to be clear, the answer is "no".

3
  • This is not really correct. All HTTP standards so far include situations when the server initiates the shutdown of the connection. As an example, datatracker.ietf.org/doc/html/rfc7230#section-6.6 more or less describes the process in selbie's answer.
    – Emil
    Commented Dec 3, 2021 at 12:21
  • Exactly. The server may initiate the close procedure of the connection, letting the client actually close it. In any scenario the client closes the socket after reading the response.
    – milan
    Commented Dec 6, 2021 at 8:08
  • Aha, so by closing you mean the last party to close. In that case you're correct. The client is always the last party to send the FIN message.
    – Emil
    Commented Dec 6, 2021 at 9:46
0

Yes, it is safe that send() then close() immediately.

the kernel will sent out all data in buffer and wait ack, then fin the socket gracefully.

0

Depends on your socket's SO_LINGER.

closesocket will wait for a graceful shutdown (everything transmitted before closing) unless you set SO_LINGER w/the l_onoff member of the linger structure nonzero and l_linger zero. In that case the connection is hard-terminated on close without waiting to send pending packets.

Ref https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-closesocket

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.