Do I need to close a socket?

后端 未结 1 769
一个人的身影
一个人的身影 2021-02-13 17:13

After sending data over a socket with Winsock, you\'re supposed to close the connection like this:

closesocket(ConnectSocket);
WSACleanup();

I\

相关标签:
1条回答
  • 2021-02-13 18:07

    One way or another, if you don't close a socket, your program will leak a file descriptor. Programs can usually only open a limited number of file descriptors, so if this happens a lot, it may turn into a problem.

    If the socket is bound to an address, no other socket will be able to bind to the same address until the socket is closed. If it's bound to a well-known port (like 25, or 80, for example), this will prevent anything else from binding to that port... which would probably be the most serious problem you might face. If it's bound to an ephemeral port, this is not as important, but, still, there are a limited number of ports and if this happens a lot then you may run out. Note that UDP sockets can be used freely without ever being bound, so this problem may not apply to UDP sockets.

    If the socket is a listening socket (listen() has been called on it), the system will continue to accept connections on this socket if you don't close it (but only up to the backlog limited specified in listen()).

    If the socket is a TCP socket and it is connected, then the TCP connection will not be closed unless the socket is closed or shutdown() is called. Therefore, in this case, you should at least make sure to call shutdown() if you can't close the socket.

    In conclusion, not closing a socket may lead to several problems which are more or less important. Generally you can expect more problems with TCP than UDP. You should definitely close sockets if possible when you are done with them!

    0 讨论(0)
提交回复
热议问题