How to find out if a socket is already in non-blocking mode in Windows?

Is there a way to find out if the socket is already in non-blocking mode on Windows?

I know that this can be done in the case of Linux, but I cannot find a way for this Windows.

All my encoding is in C. Is there a way?

+4
source share
3 answers

The only way to verify this is to do something illegal on a non-blocking socket and verify that it is not working as expected. Hardly the most durable construction.

The socket will block unless you explicitly install it without blocking using WSAIoctl or ioctlsocket with FIONBIO . I would think that it is not too difficult to check in the code. If you need to track this at runtime, the flag for each socket suggested by @jweyrich is the way to go.

+3
source

From MSDN, the return value of connect () is :

  • In a blocking socket, a return value indicates the success or failure of a connection attempt.

  • With a non-blocking socket, a connection attempt cannot be made immediately. In this case, connect will return SOCKET_ERROR , and WSAGetLastError() will return WSAEWOULDBLOCK .

0
source

Just answered the same question here , so copy-paste here in the hope that this will help:

Previously, you could call WSAIsBlocking to determine this. If you are running outdated code, this might be an option.

Otherwise, you can write a simple abstraction layer over the socket API. Since all sockets are blocked by default, you can support the internal flag and force all socket operations through your API so that you always know the state.

Here is a cross-platform snippet to set / get lock mode, although it doesn’t do exactly what you want on Windows:

 /// @author Stephen Dunn /// @date 10/12/15 bool set_blocking_mode(const int &socket, bool is_blocking) { bool ret = true; #ifdef WIN32 /// @note windows sockets are created in blocking mode by default // currently on windows, there is no easy way to obtain the socket current blocking mode since WSAIsBlocking was deprecated u_long flags = is_blocking ? 0 : 1; ret = NO_ERROR == ioctlsocket(socket, FIONBIO, &flags); #else const int flags = fcntl(socket, F_GETFL, 0); if ((flags & O_NONBLOCK) && !is_blocking) { info("set_blocking_mode(): socket was already in non-blocking mode"); return ret; } if (!(flags & O_NONBLOCK) && is_blocking) { info("set_blocking_mode(): socket was already in blocking mode"); return ret; } ret = 0 == fcntl(socket, F_SETFL, is_blocking ? flags ^ O_NONBLOCK : flags | O_NONBLOCK); #endif return ret; } 
0
source

All Articles