Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winsock MSG_DONTWAIT equivalent

While porting unix C++ code under windows and using sockets/winsock API, I am confronted with this on the server side:

recv(ClientSocket, recvbuf, recvbuflen, MSG_DONTWAIT); // UNIX code

I found from here that the equivalent of the MSG_DONTWAIT flag with WSA is to set the socket in nonblocking mode with ioctlsocket: call FIONBIO with arg != 0 (here is the documentation).

Being on the server side, I have though two sockets:

  • The socket for connecting to server:

    SOCKET ListenSocket = socket(...)
    bind(ListenSocket, ...)
    listen(ListenSocket, ...)
    ...
    
  • The temporary socket for accepting connections from clients:

    SOCKET ClientSocket;
    ClientSocket = accept(ListenSocket, ...)
    recv(ClientSocket, ...)
    ...
    

Which socket do I call ioctlsocket with? And where? (I mean where wrt these steps?)

like image 803
alleen1 Avatar asked Mar 12 '15 12:03

alleen1


1 Answers

The ListenSocket is as the name implies the socket listening on incoming (TCP/IP) connections and serves only that purpose. You call accept() later on that socket. accept() returns another socket, as soon as there is an incoming connection. This is the ClientSocket which will be used to send/recv data to/from. It is also the socket that needs to be put into non-blocking mode in order to emulate the behaviour of MSG_DONTWAIT (which is specific to Linux, don't know right now if POSIX defined this also).

So, put short, call ioctlsocket after accept and before recv on the ClientSocket.

Note: If you call accept() again you can also have more than one connection, each with a seperate socket returned by accept(). You then would use something like select() to multiplex I/O.

like image 188
Johannes Thoma Avatar answered Nov 02 '22 14:11

Johannes Thoma