Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are close() and closesocket() interchangable?

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.

like image 284
Enigma Avatar asked Feb 16 '16 19:02

Enigma


People also ask

What is the difference between closeclose () and closesocket ()?

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.

What are the semantics of the closesocket function in Java?

The semantics of the closesocket function are affected by the socket options that set members of linger structure. If the l_onoff member of the LINGER structure is zero on a stream socket, the closesocket call will return immediately and does not receive WSAEWOULDBLOCK whether the socket is blocking or nonblocking.

What is the difference between wsacancelblockingcall and closesocket?

The (blocking) Windows Socket 1.1 call was canceled through WSACancelBlockingCall . The socket is marked as nonblocking, but the l_onoff member of the linger structure is set to nonzero and the l_linger member of the linger structure is set to a nonzero timeout value. The closesocket function closes a socket.

What is the function of closesocket in WSA?

The closesocket function closes an existing socket. A descriptor identifying the socket to close. If no error occurs, closesocket returns zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError. A successful WSAStartup call must occur before using this function.


1 Answers

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.

like image 76
SergeyA Avatar answered Sep 23 '22 00:09

SergeyA