user4572253
user4572253

Reputation:

Does a socket receive stream get closed when it receives a FIN packet?

I am trying to figure out how to implement a graceful disconnection (4-way handshake).

First I send a FIN packet using the following code:

shutdown(socket, SD_SEND);

This will cause the sending socket send stream to be closed. Now when the other side receives the FIN packet, it will also send it's FIN packet:

shutdown(socket, SD_SEND);

My question is: does receiving a FIN packet automatically closes a socket receive stream, and so there is no need to explicitly closing it:

shutdown(socket, SD_RECEIVE);

Upvotes: 3

Views: 1228

Answers (1)

Metric Crapton
Metric Crapton

Reputation: 481

Let's take your question in parts:

You state:

First I send a FIN packet using the following code:

shutdown(socket, SD_SEND)

This will cause the sending socket send stream to be closed. Now when the other side receives the FIN packet, it will also send it's FIN packet:

First: The shutdown(socket} does not "close the send stream". It simply causes the socket to no longer accept send() calls. The send buffer is still there in the socket, you just can't put anything in it (because you said you wouldn't with the shutdown)

Second: You are correct that shutdown(socket, SD_SEND) should cause the socket to send a FIN. You are not correct that the other socket will send a FIN in response. The FIN your socket sends tells the other socket you will send no more data. The other socket may still have data it wants to send. The other socket will send a FIN when it also has no data to send. The other socket decides when to send a FIN.

To answer your actual question:

Receiving a FIN packet does not automatically "close a socket receive stream" as that is not something that can actually be done. The socket resources are only freed when closesocket(socket) is called. You can continue to call recv() even after a FIN has been received.

Upvotes: 2

Related Questions