From eb5dc4bcedc7503738e19ee8635f4df58f7062a2 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Thu, 22 Dec 2016 10:27:03 +0100 Subject: [PATCH] Correctly handle IPV6 in HttpProxyHandler Motivation: The HttpProxyHandler is expected to be capable of issuing a valid CONNECT request for a tunneled connection to an IPv6 host. Modifications: - Correctly format the IPV6 address. - Add unit tests Result: HttpProxyHandler works with IPV6 as well. Fixes [#6152]. --- .../src/main/java/io/netty/util/NetUtil.java | 33 ++++++++ .../test/java/io/netty/util/NetUtilTest.java | 18 +++++ .../netty/handler/proxy/HttpProxyHandler.java | 10 +-- .../handler/proxy/HttpProxyHandlerTest.java | 80 +++++++++++++++++++ 4 files changed, 133 insertions(+), 8 deletions(-) create mode 100644 handler-proxy/src/test/java/io/netty/handler/proxy/HttpProxyHandlerTest.java diff --git a/common/src/main/java/io/netty/util/NetUtil.java b/common/src/main/java/io/netty/util/NetUtil.java index a645cd70d6..a442ff4ce9 100644 --- a/common/src/main/java/io/netty/util/NetUtil.java +++ b/common/src/main/java/io/netty/util/NetUtil.java @@ -25,6 +25,7 @@ import java.io.FileReader; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; +import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; @@ -933,6 +934,38 @@ public final class NetUtil { } } + /** + * Returns the {@link String} representation of an {@link InetSocketAddress}. + *

+ * The output does not include Scope ID. + * @param addr {@link InetSocketAddress} to be converted to an address string + * @return {@code String} containing the text-formatted IP address + */ + public static String toSocketAddressString(InetSocketAddress addr) { + String port = String.valueOf(addr.getPort()); + final StringBuilder sb; + + if (addr.isUnresolved()) { + String hostString = PlatformDependent.javaVersion() >= 7 ? addr.getHostString() : addr.getHostName(); + sb = newSocketAddressStringBuilder(hostString, port, !isValidIpV6Address(hostString)); + } else { + InetAddress address = addr.getAddress(); + String hostString = toAddressString(address); + sb = newSocketAddressStringBuilder(hostString, port, address instanceof Inet4Address); + } + return sb.append(':').append(port).toString(); + } + + private static StringBuilder newSocketAddressStringBuilder(String hostString, String port, boolean ipv4) { + if (ipv4) { + // Need to include enough space for hostString:port. + return new StringBuilder(hostString.length() + 1 + port.length()).append(hostString); + } + // Need to include enough space for [hostString]:port. + return new StringBuilder( + hostString.length() + 3 + port.length()).append('[').append(hostString).append(']'); + } + /** * Returns the {@link String} representation of an {@link InetAddress}. *