【问题标题】:SocketException when using preferIPv6Addresses使用 preferIPv6Addresses 时出现 SocketException
【发布时间】:2020-03-03 05:10:24
【问题描述】:

所以我有一个要求,我需要访问一个 URL,同时更喜欢 IPV6(如果有的话)。

这是我的一段代码。

private HttpURLConnection getConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setConnectTimeout(15 * 1000);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("User-Agent", "Mozilla/4.76");
    conn.setUseCaches(false);
    return conn;
}

我正在通过Buffered Reader 读取连接输出。

HttpURLConnection conn = getConnection(new URL(API + urlParameters));
return new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();

问题发生在 BufferedReader 引发错误

net.SocketException: Network is unreachable: connect

但是当我从我的应用程序中删除此代码块时,该程序按预期工作。 System.setProperty("java.net.preferIPv6Addresses", "true");

但是,即使用户可以使用IPv6,它当然也会发送IPv4 IP 地址,如果用户不能使用IPv6,它会发送IPv6 IP 地址,它将使用IPv4,我正在使用 cloudflare 记录 IP,默认情况下,cloudflare 需要来自浏览器的 IPv6

【问题讨论】:

标签: java http httpurlconnection ipv6


【解决方案1】:

在此之前使用此代码测试 IPv6 支持:

private static boolean supportsIPv6() throws SocketException {
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        Iterator<InterfaceAddress> e2 = e.nextElement().getInterfaceAddresses().iterator();
        while (e2.hasNext()) {
            final InetAddress ip = e2.next().getAddress();
            if (ip.isLoopbackAddress() || ip instanceof Inet4Address){
                continue;
            }
            return true;
        }
    }
    return false;
}

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多