How to view/change socket connection timeout on Li

2019-02-12 23:13发布

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

4条回答
Emotional °昔
2楼-- · 2019-02-12 23:46

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.

查看更多
迷人小祖宗
3楼-- · 2019-02-12 23:48

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.

查看更多
疯言疯语
4楼-- · 2019-02-12 23:55

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.

查看更多
我想做一个坏孩纸
5楼-- · 2019-02-13 00:05

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

查看更多
登录 后发表回答