开发者

Calling shutdown and closesocket twice on same socket

In my application I call shutdown and closesocket functions twice on the same socket. I know this is not right thing to do and I have to ensure that these functions are called only once. But why don't either of these calls fail when called a second time?

If the handle of m_Socket is 1500, then what will it's value be when shu开发者_JS百科tdown and closesocket functions are called on it?

shutdown(m_SocServer, 2);
closesocket(m_SocServer);


First one must distinguish two different things:

  1. Performing operations on a socket, some of which may bring it in an unusable state.
  2. Terminating the socket handle.

Calling shutdown with parameter 2 (which is SD_BOTH) is (1). That is, you flush all the pending out buffer, plus discard all the receive buffer. So that you can't read/write anymore. However you still hold a valid socket handle. You still may query/set its options if you want. For instance, one could call getpeername on it to discover the address you were connected to. Also, depending on the implementation, calling shutdown again doesn't have to result in an error. Maybe it has an accumulative effect.

On the other hand calling closesocket is (2). Once you called it - you can't do anything with that socket handle. It's now invalid.

If you socket has a value of 1500 - it will still have it, even after a call to closesocket. Because it's just a variable. It's like asking what value will have the pointer after you delete it.

However this socket value (1500) is no more valid. You can't call any socket function with this value.

Moreover, if you create another socket meanwhile - it's very likely to receive the same number. Here you may find yourself in a more severe problem - doing actions on another socket without noticing it.

For some it's a good practice assigning INVALID_SOCKET value to a socket variable right after you call closesocket on it.

P.S. Perhaps calling shutdown + closesocket don't fail specifically because you're closing another socket.


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

Once you call closesocket, that socket identifier is free and could be returned again by another call to socket. If you call closesocket again, you are not closing your original socket but the newly reopened one


They do fail. Try to following snippet.

SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
closesocket(s);   // OK

shutdown(s, 2);   // fails
closesocket(s);   // fails
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜