Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Nonblocking socket for WinSocks and *nix

In C/C++, how would I turn a blocking socket into a non blocking socket in both WinSocks and *nix; so that select() would work correctly. You can use the pre-processor for the platform specific code.

like image 865
Christopher Dolan Avatar asked Oct 04 '08 19:10

Christopher Dolan


People also ask

How do I change a socket to nonblocking?

Change a socket to nonblocking mode using the ioctl() call that specifies command FIONBIO and a fullword (four byte) argument with a nonzero binary value. Any succeeding socket calls against the involved socket descriptor are nonblocking calls.

How do I create a nonblocking socket in C++?

To mark a socket as non-blocking, we use the fcntl system call. Here's an example: int flags = guard(fcntl(socket_fd, F_GETFL), "could not get file flags"); guard(fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK), "could not set file flags"); Here's a complete example.

What is blocking and nonblocking socket?

A socket can be in "blocking mode" or "nonblocking mode." The functions of sockets in blocking (or synchronous) mode do not return until they can complete their action. This is called blocking because the socket whose function was called cannot do anything — is blocked — until the call returns.

Is socket accept blocking?

If no pending connections are present on the queue, and the socket is not marked as nonblocking, accept() blocks the caller until a connection is present. If the socket is marked nonblocking and no pending connections are present on the queue, accept() fails with the error EAGAIN or EWOULDBLOCK.


2 Answers

On linux:

fcntl(fd, F_SETFL, O_NONBLOCK);

Windows:

u_long on = 1;
ioctlsocket(fd, FIONBIO, &on);
like image 148
hazzen Avatar answered Nov 15 '22 09:11

hazzen


select() is supposed to work on blocking sockets. It returns when a read() would return immediately, which is always the case with non-blocking sockets.

like image 36
wnoise Avatar answered Nov 15 '22 11:11

wnoise