3

I saw a piece of code like this, which was used to close a socket.

`//a TCP socket is created: sockfd 
struct linger ling;
ling.l_onoff = 1;
ling.l_linger = 0;
setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
......
//when need to close the socket
if(sockfd>0)
{
    shutdown(sockfd, SHUT_RDWR);
    close(sockfd);
}
else
{
    //some error message
}`

I have three questions:

  1. Why need call shutdown and close at the same time to close the socket? From Wireshark, It seems that a FIN would be sent, then a RST is sent.
  2. In this way, a TIME_WAIT state could be avoid?
  3. When shutdown sockfd, the file descriptor is still available? there is no error occurred when call close function.
user207421
  • 305,947
  • 44
  • 307
  • 483
Boson Rao
  • 31
  • 2
  • Discussion if shutdown() vs close() vs both is here: http://stackoverflow.com/questions/4160347/close-vs-shutdown-socket – TonyB Nov 03 '16 at 02:38

1 Answers1

3

Why need call shutdown and close at the same time to close the socket?

Normally you don't. The only exception I'm aware of is if you have inherited the socket, or a child process has, and yo want to ensure the FIN is sent now. Or if you want to engage in a FIN exchange protocol with the peer to be sure you both get to end of stream at the same time, which involves shutdown and then read. Not as above.

In this way, a TIME_WAIT state could be avoided?

No.

When shutdown sockfd, the file descriptor is still available?

Yes.

user207421
  • 305,947
  • 44
  • 307
  • 483