因此,我有一个要求,我需要访问一个网址,而首选的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");
但当然它会发送IPv4 IP地址,即使用户可以使用IPv6,我如何才能让它发送IPv6 IP如果用户不能使用IPv6,它将使用IPv4,我正在使用cloudflare来记录IP,默认情况下,cloudflare需要浏览器中的IPv6。
发布于 2019-11-25 22:43:05
在使用以下代码测试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;
}https://stackoverflow.com/questions/58734866
复制相似问题