Call shutdown and close twice on the same socket

In my application, I call shutdown and closesocket functions twice on the same socket. I know this is wrong, and I must ensure that these functions are called only once. But why would not one of these calls be called when called a second time?

If the m_Socket descriptor is 1500 , then what will it know when the shutdown and closesocket functions are called on it?

 shutdown(m_SocServer, 2); closesocket(m_SocServer); 
+2
source share
3 answers

First you need to distinguish between two different things:

  • Performing socket operations, some of which may lead to an unusable state.
  • Completion of the socket descriptor.

The shutdown call with parameter 2 (which is equal to SD_BOTH ) is equal to (1). That is, you clear the entire incomplete buffer, and also delete the entire receive buffer. So you can no longer read / write. However, you still keep a valid socket descriptor. You can still request / set your parameters if you want. For example, you could call getpeername to open the address to which you are connected. In addition, depending on the implementation, the shutdown call should not again result in an error. Perhaps it has a cumulative effect.

On the other hand, the closesocket call is (2). Once you have called it, you cannot do anything with this socket descriptor. It is now invalid.

If your socket has a value of 1500, it will still receive it, even after calling closesocket . Because it is just a variable. He would like to ask what value the pointer will have after you delete .

However, this socket value (1500) is no longer valid. You cannot call any socket function with this value.

Also, if you create another socket in the meantime, it will most likely get the same number. Here you may encounter a more serious problem - doing actions on another socket without noticing it.

For some, it's a good practice to assign an INVALID_SOCKET value to a socket variable immediately after calling closesocket on it.

PS Perhaps the shutdown + closesocket does not work specifically because you are closing another socket.

+7
source

Whether you get an error or not after calling closesocket for the first time depends on what the rest of your code does.

Once you call closesocket , this socket id is free and can be returned again by another socket call. If you call closesocket again, you are not closing your original socket, but just reopening it

+5
source

They fail. Try the following snippet.

 SOCKET s = socket(AF_INET, SOCK_STREAM, 0); closesocket(s); // OK shutdown(s, 2); // fails closesocket(s); // fails 
+1
source

Source: https://habr.com/ru/post/1481703/


All Articles