Skip to content

Commit

Permalink
Preserve the host name of address when parsing /etc/hosts file
Browse files Browse the repository at this point in the history
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
  • Loading branch information
trustin authored and normanmaurer committed Feb 4, 2016
1 parent 075a54a commit ef0e053
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions resolver/src/main/java/io/netty/resolver/HostsFileParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import static io.netty.util.internal.ObjectUtil.*;

Expand All @@ -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() {
Expand Down Expand Up @@ -126,7 +129,7 @@ public static Map<String, InetAddress> parse(Reader reader) throws IOException {

// split
List<String> lineParts = new ArrayList<String>();
for (String s: line.split("[ \t]+")) {
for (String s: WHITESPACES.split(line)) {
if (!s.isEmpty()) {
lineParts.add(s);
}
Expand All @@ -145,21 +148,23 @@ public static Map<String, InetAddress> parse(Reader reader) throws IOException {
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);
}
}
}

Expand Down

0 comments on commit ef0e053

Please sign in to comment.