我们的一个 Java 程序启动时,它只监听 IPv6 (8080)
例如
# netstat -ntpl
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN -
tcp6 0 0 :::8080 :::* LISTEN -
tcp6 0 0 :::22 :::* LISTEN -
问题是无法从外部访问(本地主机除外),为了解决这个问题,我手动添加了
-Djava.net.preferIPv4Stack=true
但这使得该程序仅适用于 IPv4 网络。
是否可以像上面的sshd一样,同时支持IPv4和IPv6?
最佳答案
我怀疑这不是 Java 编程问题,而是操作系统网络堆栈/操作系统网络配置问题:
http://coding.derkeiler.com/Archive/Java/comp.lang.java.help/2009-09/msg00087.html
On some OSes, a single native TCP socket can listen to a port on both IPv4 and IPv6 simultaneously. It is able to accept connections from remote IPv4 and from remote IPv6 clients. On other OSes (such as WinXP) an OS native socket CANNOT do that, but can only accept from IPv4 or IPv6, not both. On those OSes, it is necessary to have two listen sockets in order to be able to accept connections from both remote IPv4 and IPv6 clients, one socket to listen for IPv4 connections and one for IPv6.
Windows 7 和 Windows Server 2008 可以很好地处理双堆栈; Windows XP 没那么多:)
您似乎在使用 Linux - 大多数现代 Linux 台式机和服务器也可以毫无问题地处理双 ipv4 ipv6。
这是一篇关于互操作性的好文章:
您知道如何为您的 Java 应用程序“关闭”IPV6:-Djava.net.preferIPv4Stack=true
您也可以像这样强制您的服务器使用 IPV6:echo 0 >/proc/sys/net/ipv6/bindv6only
这可以说是您最好的来源:
除非您受到外部网络问题的限制,否则您绝对应该能够完成您想要的(至少在 Java 编程级别):
Nodes) V4 Only V4/V6 V6 Only
------- ----- -------
V4 Only x x
V4/V6 x x x
V6 Only x x
附言:
这是另一个很好的链接,它解释了在套接字级别发生的事情。它不是 Java(它是 C),但示例原则完全适用:
关于java - 如何在 Java 上同时支持 IPv4 和 IPv6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10378471/