ctor
ctor

Reputation: 6088

Modify connect() timeout period

I have done a bit of searching and can't seem to find the answer I'm looking for, the only answers I could find were to use select to see if the socket had timed out which is what I am already doing.

What I want to know is there anyway to change the length of time before connect() would timeout? I am currently using select() which returns with errno set to EINPROGRESS until eventually returning with ETIMEDOUT. Is there anyway I can change the amount of time it takes before this ETIMEDOUT would occur? Currently it happens after about 60 seconds. I have tried adjusting the timeout value I pass into the select() call however, this only affects how long it takes before select() will time out.

Upvotes: 9

Views: 1734

Answers (2)

user207421
user207421

Reputation: 310909

  1. Create the socket.
  2. Put it into non-blocking mode.
  3. Issue connect().
  4. Call select() or poll() or epoll(), specifying your desired timeout, and specifying the socket as a writefd, i.e. blocking until the timeout expires or the socket becomes writable.
  5. If the timeout expires, close the socket etc.
  6. Otherwise get the last error on the socket via getsockopt() and see if it's zero. If so, the connection has succeeded, otherwise it has failed.

Note that you cannot increase the connect timeout beyond the platform default (about a minute) by this means, but you can decrease it.

Upvotes: 4

user2471020
user2471020

Reputation:

setsockopt(3) allows you to set this: http://linux.die.net/man/3/setsockopt

Slightly confusing, the timeout values are actually properties of the socket.

The options you are looking for are: SO_SNDTIMEO and SO_RCVTIMEO

EDIT As stated in the comments, this doesn't work for connect. Here is why: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout As a solution it is suggested to set limits on the amount of retry SYN packets the kernel sends to establish the connection after the initial handshake failed. The time is doubled since the last retry, which means a) you can only set the amount of retries, which indirectly adds up to a connect timeout value and b) this is OS specific and system wide. Not a solution for you probably....

Upvotes: 1

Related Questions