Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

It is BTW not entirely correct, that Linux and Windows behave here differently. Besides the initial SYN retries (which can be configured on Linux and Windows) the neighbour state as well as other routers sending RST packets also play a role.

If a connection attempt on Windows fails immediatelly it is likely that it was eighter RSTed by a router or the neighbour was recognized as unreachable on ARP level. Try the arp -a -v command on Windows to see the unreachable hosts - which get rejected quickly.

For Linux you would use ip neigh to list the reachability state of stations on your local network.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top