From ef0e05320272be28940db2ecb07be7d70a50e958 Mon Sep 17 00:00:00 2001 From: Trustin Lee Date: Thu, 4 Feb 2016 20:23:48 +0900 Subject: [PATCH] Preserve the host name of address when parsing /etc/hosts file Motivation: When an InetNameResolver resolves a name, it is expected to reserve the requested host name in the resolved InetAddress. DefaultHostsFileEntriesResolver does not preserve the host name. For example, resolving 'localhost' will return an InetAddress whose address is '127.0.0.1', but its getHostString() will not return 'localhost' but just '127.0.0.1'. Modifications: Fix the construction of parsed InetAddresses in HostsFileParser Result: Host name is preserved in the resolved InetAddress --- .../java/io/netty/resolver/HostsFileParser.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/resolver/src/main/java/io/netty/resolver/HostsFileParser.java b/resolver/src/main/java/io/netty/resolver/HostsFileParser.java index 38272d3dac..0e8b9163c7 100644 --- a/resolver/src/main/java/io/netty/resolver/HostsFileParser.java +++ b/resolver/src/main/java/io/netty/resolver/HostsFileParser.java @@ -31,6 +31,7 @@ import java.util.Collections; import java.util.List; import java.util.HashMap; import java.util.Map; +import java.util.regex.Pattern; import static io.netty.util.internal.ObjectUtil.*; @@ -43,6 +44,8 @@ public final class HostsFileParser { private static final String WINDOWS_HOSTS_FILE_RELATIVE_PATH = "\\system32\\drivers\\etc\\hosts"; private static final String X_PLATFORMS_HOSTS_FILE_PATH = "/etc/hosts"; + private static final Pattern WHITESPACES = Pattern.compile("[ \t]+"); + private static final InternalLogger logger = InternalLoggerFactory.getInstance(HostsFileParser.class); private static File locateHostsFile() { @@ -126,7 +129,7 @@ public final class HostsFileParser { // split List lineParts = new ArrayList(); - for (String s: line.split("[ \t]+")) { + for (String s: WHITESPACES.split(line)) { if (!s.isEmpty()) { lineParts.add(s); } @@ -145,21 +148,23 @@ public final class HostsFileParser { continue; } - InetAddress inetAddress = InetAddress.getByAddress(ipBytes); - // loop over hostname and aliases for (int i = 1; i < lineParts.size(); i ++) { String hostname = lineParts.get(i); if (!entries.containsKey(hostname)) { // trying to map a host to multiple IPs is wrong // only the first entry is honored - entries.put(hostname, inetAddress); + entries.put(hostname, InetAddress.getByAddress(hostname, ipBytes)); } } } return entries; } finally { - buff.close(); + try { + buff.close(); + } catch (IOException e) { + logger.warn("Failed to close a reader", e); + } } }