Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a TCP socket to be non-blocking?

Tags:

c

sockets

How do you make a socket non-blocking?

I am aware of the fcntl() function, but I've heard it's not always reliable.

like image 702
Sachin Chourasiya Avatar asked Oct 09 '09 12:10

Sachin Chourasiya


People also ask

Is TCP socket blocking?

By default, TCP sockets are in "blocking" mode. For example, when you call recv() to read from a stream, control isn't returned to your program until at least one byte of data is read from the remote site. This process of waiting for data to appear is referred to as "blocking".

Are sockets blocking by default?

The default mode of socket calls is blocking. A blocking call does not return to your program until the event you requested has been completed.

What is non-blocking socket?

In blocking socket mode, a system call event halts the execution until an appropriate reply has been received. In non-blocking sockets, it continues to execute even if the system call has been invoked and deals with its reply appropriately later.

How can you tell if a socket is blocking or non-blocking?

From MSDN, the return value of connect(): On a blocking socket, the return value indicates success or failure of the connection attempt. With a nonblocking socket, the connection attempt cannot be completed immediately. In this case, connect will return SOCKET_ERROR , and WSAGetLastError() will return WSAEWOULDBLOCK.


1 Answers

fcntl() has always worked reliably for me. In any case, here is the function I use to enable/disable blocking on a socket:

#include <fcntl.h>  /** Returns true on success, or false if there was an error */ bool SetSocketBlockingEnabled(int fd, bool blocking) {    if (fd < 0) return false;  #ifdef _WIN32    unsigned long mode = blocking ? 0 : 1;    return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? true : false; #else    int flags = fcntl(fd, F_GETFL, 0);    if (flags == -1) return false;    flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);    return (fcntl(fd, F_SETFL, flags) == 0) ? true : false; #endif } 
like image 120
Jeremy Friesner Avatar answered Sep 20 '22 13:09

Jeremy Friesner