Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to close a socket?

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?

like image 809
1'' Avatar asked Jun 12 '13 23:06

1''


1 Answers

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!

like image 58
Celada Avatar answered Sep 24 '22 15:09

Celada