IPv6 环回地址 http://0:0:0:0:0:0:0:1 - 浏览器无法连接。方法 getRemoteHost()

IPv6 loopback address http://0:0:0:0:0:0:0:1 - browser can't connect. Method getRemoteHost()

方法String domain = request.getRemoteHost();returns0:0:0:0:0:0:0:1IPv6地址。网卡配置为支持IPv6协议,Firefox也是:network.dns.disableIPv6 false,安装Java1.8.0_141-b1564位。但是如果我输入 http://0:0:0:0:0:0:0:1 它会显示错误或显示 Google (??) 上的结果。如果我输入 localhost127.0.0.1 它会显示我项目的网页。如何修复?我的目标不是禁用 IPv6,而是同时支持 IPv4 和 IPv6 协议。

建议的解决方案是添加方括号:http://[0:0:0:0:0:0:0:1]。它正在工作。但现在我们必须手动添加括号,并且仅当协议为 IPv6 时。也许应该更新 getRemoteHost() 以更好地支持 IPv6?

我在网络资源标识符中找到了有关文字 IPv6 地址的信息 here:

Colon (:) characters in IPv6 addresses may conflict with the established syntax of resource identifiers, such as URIs and URLs. The colon has traditionally been used to terminate the host path before a port number.[8] To alleviate this conflict, literal IPv6 addresses are enclosed in square brackets in such resource identifiers, for example:

http://[2001:db8:85a3:8d3:1319:8a2e:370:7348]/

When the URL also contains a port number the notation is:

https://[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443/

看来 Java 有问题...?现在正在研究 IPv6 正则表达式..

找到一个简单的解决方案:

public static boolean isIPv6(String IP) throws UnknownHostException {
    InetAddress address = InetAddress.getByName(IP);
    return address instanceof Inet6Address;
}

但是如果有一个方法getRemoteHost(true | false)来获取带括号或不带括号的 IPv6 地址,那就太好了。

如果您向 Java 询问主机名,您将得到一个主机名,而不是 URI 片段。没有什么不妥。如果你真的想要一个URI,你应该要求一个URI:

String host = "::1", path = "/";
URI uri = new URI("http", host, path, null);
System.out.println("URI: " + uri);

将打印

URI: http://[::1]/

但是,如果您改为手动构造 URI 字符串,则有责任在必要时添加括号。