如何在 Linux 上查看/更改套接字连接超时?

发布于 2024-07-25 10:17:19 字数 363 浏览 2 评论 0原文

在 Java 中创建 Socket 时:

new Socket(host, port);

Socket 构造函数将在返回之前尝试连接到 host:port。 在 Windows 上,对于无法访问的主机,此操作几乎会立即失败,但对于 Linux,套接字可能需要长达 5 分钟的时间才会超时。

我知道如果我可以控制创建套接字,我可以这样做:

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

但我宁愿让操作系统使用合理的默认值。 有没有办法在 Linux 上更改此设置?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风流物 2024-08-01 10:17:19

我想你想要/proc/sys/net/ipv4/tcp_syn_retries。 默认值通常为 5 或 6,大约为 3 分钟。

请注意,这些是系统范围的。

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.

说谎友 2024-08-01 10:17:19

我建议不要更改操作系统设置,因为它可能会意外影响其他应用程序。 Socket.setSoTimeout() 方法也可能对您有帮助。

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

过去的过去 2024-08-01 10:17:19

顺便说一句,Linux 和 Windows 在这里的行为有所不同,这并不完全正确。 除了初始 SYN 重试(可以在 Linux 和 Windows 上配置)之外,邻居状态以及发送 RST 数据包的其他路由器也发挥作用。

如果 Windows 上的连接尝试立即失败,则很可能是路由器对其进行了 RST 处理,或者邻居在 ARP 级别上被识别为无法访问。 在 Windows 上尝试使用 arp -a -v 命令来查看无法访问的主机 - 这些主机很快就会被拒绝。

对于 Linux,您可以使用 ip neigh 列出本地网络上站点的可达性状态。

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.

作死小能手 2024-08-01 10:17:19

据我了解,这取决于系统的 TCP/IP 默认超时(默认为 24​​0 秒?)...一种选择是尝试调整这些超时,但这可能会影响同一台计算机上依赖超时值的任何其他程序。 在这种情况下,简单地降低 Java connect() 调用中的“超时”值可能会更安全。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文