I am using timeout for sending and receiving data on a socket. I found that timeout can be achieved either by setting socket to non-blocking mode and using select
or by using setsockopt
with SO_SNDTIMEO
/SO_RCVTIMEO
option.
What are the differences between these two methods and is there any reason to prefer one implementation over the other both for Linux (Redhat) and Windows?

- 65
- 6
-
Does this help you somehow? https://stackoverflow.com/a/36641978/4885321 – alagner Jun 08 '21 at 06:20
1 Answers
What are the differences between these two methods and is there any reason to prefer one implementation over the other both for Linux (Redhat) and Windows?
For Linux, the differences seem to be rather small:
Specify the receiving or sending timeouts until reporting an error. The argument is a struct timeval. If an input or output function blocks for this period of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK, or EINPROGRESS (for connect(2)) just as if the socket was specified to be nonblocking. If the timeout is set to zero (the default) then the operation will never timeout. Timeouts only have effect for system calls that perform socket I/O (e.g., read(2), recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for select(2), poll(2), epoll_wait(2), and so on.
However, you do not have the handy property to multiplex multiple connections at the same time as you would do with e.g. select
.
For Windows, the differences are more severe:
The timeout, in milliseconds, for blocking send calls. The default for this option is zero, which indicates that a send operation will not time out. If a blocking send call times out, the connection is in an indeterminate state and should be closed. If the socket is created using the WSASocket function, then the dwFlags parameter must have the WSA_FLAG_OVERLAPPED attribute set for the timeout to function properly. Otherwise the timeout never takes effect.
So after the timeout, the socket is unusable (which might not be the behavior you want).
For the sole reason that this behavior differs between the two Berkely socket implementations, I would not recommend using setsockopt(SO_SNDTIMEO/SO_RCVTIMEO)
but use the facilities that have been created for this very reason, e.g. select
, or even better, a proper network socket library like boost::asio.

- 7,493
- 1
- 29
- 45
-
If a send times out the connection is probably in an 'indeterminate state' on all platforms, but it isn't compulsory to close it. It might be still working OK in the receive direction. – user207421 Jun 08 '21 at 07:31
-
@user207421 No, this is not correct in the case of Winsock, as stated in the quote of my answer. Acting against the recommendation of MSDN certainly is a very bad idea. – Jodocus Jun 30 '21 at 12:58