Are close () and closesocket () interchangeable?

I saw a lot of answers here that say use close () to destroy the socket, but the manual that I used from msdn does I use closesocket (). I wonder if there is a difference and if there are reasons to use one or the other.

In both cases, I see a suggestion to use shutdown () so that everything is fine and good.

+7
c ++ networking sockets winsock2
source share
1 answer

close() is a * nix function. It will work with any file descriptor, and sockets in * nix is ​​an example of a file descriptor, so it will close sockets correctly.

closesocket() is a Windows-specific function that works specifically with sockets. Sockets on Windows do not use nix-type file descriptors, socket() instead returns a handle to the kernel object, so it should be closed using closesocket() .

I find it rather shameful that BSD sockets do not include a specific copy of the socket function that can be used anywhere - but this is life.

Last, but not least, don’t confuse the shutdown 'socket with closing the socket. shutdown() stops transmission on the socket, but the socket remains on the system and all resources associated with it remain. You still need to close the socket after it is closed.

+9
source share

All Articles