2

I am implementing a simple proxy application in which I always receive data from one end and send to the other end.

In such a case, once I am sure that I am done with receiving all the data from the incoming leg, can I call directly close( ) without calling shutdown( )? If I do so, will close( ) ensure that all the data is delivered to the destination on the outgoing leg and received by the application at the destination?

Or in such a case, is it mandatory that I initiate a shutdown before I initiate a close?

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Check http://stackoverflow.com/questions/8874021/close-socket-directly-after-send-unsafe - close should make it so that data is delivered barring no major network problem. – coyotte508 Jun 07 '16 at 17:51

1 Answers1

0

can I call directly close() without calling shutdown()

You can. shutdown is only necessary if you would like to half-close the connection (i.e. read or write end).

will the close( ) ensure that all the data is delivered to the destination on the outgoing leg and received by the application at the destination

close does in the background what a blocking send does, no more, no less. If that background send fails though, you will not get any error indication.

There is also SO_LINGER socket option you can tweak if necessary:

  SO_LINGER
         Sets or gets the SO_LINGER option.  The  argument  is  a  linger
         structure.

             struct linger {
                 int l_onoff;    /* linger active */
                 int l_linger;   /* how many seconds to linger for */
             };

         When  enabled,  a  close(2) or shutdown(2) will not return until
         all queued messages for the socket have been  successfully  sent
         or  the  linger  timeout  has been reached.  Otherwise, the call
         returns immediately and the closing is done in  the  background.
         When  the socket is closed as part of exit(2), it always lingers
         in the background.
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • 1
    Small note on `shutdown()`. It will affect all copies of the socket such as those created with `dup()`, `dup2()` or `fork()`. The `close()` function affects only one copy of the socket. If it is not closing the last copy then the other copies of the socket continue to operate as normal. – Zan Lynx Dec 07 '16 at 17:56