Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Win32, is there a way to test if a socket is non-blocking?

In Win32, is there a way to test if a socket is non-blocking?

Under POSIX systems, I'd do something like the following:

int is_non_blocking(int sock_fd) {
    flags = fcntl(sock_fd, F_GETFL, 0);
    return flags & O_NONBLOCK;
}

However, Windows sockets don't support fcntl(). The non-blocking mode is set using ioctl with FIONBIO, but there doesn't appear to be a way to get the current non-blocking mode using ioctl.

Is there some other call on Windows that I can use to determine if the socket is currently in non-blocking mode?

like image 719
Daniel Stutzbach Avatar asked Mar 30 '11 17:03

Daniel Stutzbach


People also ask

How can you tell if a socket is 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.

How do I make a socket non-blocking?

A blocking accept() call does not return to your program until a client connects to your socket program. 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.

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.

Is socket read 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".


1 Answers

A slightly longer answer would be: No, but you will usually know whether or not it is, because it is relatively well-defined.

All sockets are blocking unless you explicitly ioctlsocket() them with FIONBIO or hand them to either WSAAsyncSelect or WSAEventSelect. The latter two functions "secretly" change the socket to non-blocking.

Since you know whether you have called one of those 3 functions, even though you cannot query the status, it is still known. The obvious exception is if that socket comes from some 3rd party library of which you don't know what exactly it has been doing to the socket.

Sidenote: Funnily, a socket can be blocking and overlapped at the same time, which does not immediately seem intuitive, but it kind of makes sense because they come from opposite paradigms (readiness vs completion).

like image 125
Damon Avatar answered Oct 17 '22 07:10

Damon