Do I need to close a socket?

自闭症网瘾萝莉.ら 提交于 2021-02-06 15:26:13

问题


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

closesocket(ConnectSocket);
WSACleanup();

I'm writing an API that sends data over a socket. If I have to close the socket afterwards, I need to add a function to the API so that users can say when they're done getting data. Is it a problem if I don't close the socket, for convenience?


回答1:


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!



来源:https://stackoverflow.com/questions/17077096/do-i-need-to-close-a-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!