在同一个套接字上调用shutdown和closesocket两次 [英] Calling shutdown and closesocket twice on same socket

查看:1457
本文介绍了在同一个套接字上调用shutdown和closesocket两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我在相同的套接字上调用shutdown和closesocket函数两次。我知道这是不正确的事情,我必须确保这些函数只调用一次,但为什么不关闭套接字或关闭套接字失败时调用第二次。

In my application i am calling shutdown and closesocket function twice on 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 doesnt the shutdown socket or close socket fail when called second time.

如果m_Socket的值为1500,则当关闭时会调用它的值,并且像这样调用closesocket函数。

If m_Socket is having a value of 1500 what will its value be when shutdown and closesocket functions are called like this.

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


推荐答案

第一个必须区分两种不同的东西:

First one must distinguish two different things:


  1. 在套接字上执行操作,其中一些可能会使其处于无法使用的状态。


使用参数2调用 shutdown c> SD_BOTH )为(1)。也就是说,您刷新所有待处理的缓冲区,并丢弃所有接收缓冲区。所以,你不能读/写了。但是,您仍然拥有有效的套接字句柄。如果需要,您仍然可以查询/设置其选项。例如,可以调用 getpeername 来发现您连接的地址。
此外,根据实现,再次调用 shutdown 不会导致错误。也许它有累积效应。

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.

另一方面,调用 closesocket 是(2)。一旦你调用它 - 你不能做任何东西与该套接字句柄。

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.

如果你的socket的值为1500,即使调用 closesocket 。因为它只是一个变量。这就像在 delete 之后询问什么值会有指针。

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.

对于某些是一个很好的习惯, INVALID_SOCKET $

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

PS

这篇关于在同一个套接字上调用shutdown和closesocket两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆