views:

4427

answers:

3

When creating a Socket in Java:

new Socket(host, port);

The Socket constructor will try to connect to host:port before returning. On Windows, this fails almost immediately for unreachable hosts but for Linux it can take up to 5 minutes for the Socket to timeout.

I'm aware that if I have control over creating the Sockets, I can do:

Socket s = new Socket();
s.bind(..);
s.connect(.., timeout);

but I'd rather have the OS use a reasonable default value. Is there a way to change this setting on Linux?

Thanks

A: 

It's my understanding that this depends on the system's TCP/IP default timeout (240 seconds by default?)... one option is to try tweaking those, however this could affect any other programs on the same machine which rely on the timeout value. In which case, it might be safer to simply lower the "timeout" value in your Java connect() call, instead.

DreadPirateShawn
+2  A: 

I think you want /proc/sys/net/ipv4/tcp-syn-retries. The default is usually 5 or 6 which comes out to around 3 minutes.

Note that these are system-wide.

Duck
How is the time between each retry set? It seems to increase exponentially with each retry. Where is this set?
Kevin
The intervals do increase, at least up to a point. My memory is failing me here. I don't remember if that is BSD thing or TCP and I am not sure if Linux gives you a way to control it.
Duck
The intervals are controlled by values called rtoMin,rtoMax and rtoInitial where rto stands for Round Trip Timeout. Basically, it denotes the time it would take for a packet to do a round trip. So, if when TCP sends the first msg, it would wait for rtoInitial time. If it fails to get a response, it will double the rto (and add some jitter value) and then try again. This will continue till maxRetries. The current rto value will never go past rtoMax.
Aditya Sehgal
@Aditya Thanks for the clarification. I couldn't remember if the TCP algorithms came into play during the connect phase or if the OS was setting arbitrary timers.
Duck
Thanks to you both
Kevin
+1  A: 

I would advise against changing OS settings as it might affect other applications unexpectedly. The Socket.setSoTimeout() method might help you too.

kd304
May I ask the reason for the downvote so I could learn from it?
kd304