Are close() and closesocket() interchangable?

Enigma picture Enigma · Feb 16, 2016 · Viewed 15.4k times · Source

I've seen a lot of answers here that say to use close() to destroy a socket but the guide I used from msdn has me using closesocket(). I'm wondering if there is a difference and if there are reasons to use one or the other.

In both cases, I am seeing the suggestion to use shutdown() so that's all well and good.

Answer

SergeyA picture SergeyA · Feb 16, 2016

close() is a *nix function. It will work on any file descriptor, and sockets in *nix are an example of a file descriptor, so it would correctly close sockets as well.

closesocket() is a Windows-specific function, which works specifically with sockets. Sockets on Windows do not use *nix-style file descriptors, socket() returns a handle to a kernel object instead, so it must be closed with closesocket().

I find it rather shameful that BSD-sockets do not include specific counterpart to socket function, which could be used anywhere - but such is life.

The last, but not the least, do not confuse shutdown'ing a socket with closing the socket. shutdown() stops transmission on a socket, but the socket remains in the system and all resources associated with it remain. You still need to close the socket after shutting it down.