Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set sockets to blocking mode in Windows?

I'm doing some fairly simple cross-platform TCP socket programming. I have unfortunately found out that when compiled on Windows, my sockets are non-blocking by default, while on OS X they are blocking by default. How do I force a socket into blocking mode on Windows? Do they normally default to non-blocking mode or is something terribly wrong?

My code is based in part on these simple examples: http://cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoClient.c http://cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoServer.c


2 Answers

I believe this reference may help; note, in particular, that

Although blocking operations on sockets are supported under Windows Sockets, their use is strongly discouraged. Programmers who are constrained to use blocking mode -- for example, as part of an existing application which is to be ported -- should be aware of the semantics of blocking operations in Windows Sockets.

If you're fully aware of the zillion issues listed here, and find dealing with all of them preferable to designing your program to fit in well with Windows rather than being a half-beeped port from Unix, go right ahead with a ioctlsocket call with the cmd argument set to FIONBIO and the third argument pointing to a longword worth 0. But, don't say you weren't warned;-).

like image 107
Alex Martelli Avatar answered Oct 23 '25 15:10

Alex Martelli


No, plain old BSD style sockets are not non-blocking by default on Windows. See the examples in the Winsock Programmer's FAQ.

If you use MFC and its CAsyncSocket mess, then yes, it's all non-blocking, but that's a separate issue.

like image 39
Warren Young Avatar answered Oct 23 '25 15:10

Warren Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!