Skip to content

Commit

Permalink
Normalize IDN hostnames to punycode before DNS resolution to prevent …
Browse files Browse the repository at this point in the history
…UnknownHostException during connection.
  • Loading branch information
arturobernalg committed Jan 6, 2025
1 parent 9e3559e commit 3c78786
Showing 1 changed file with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@
*/
package org.apache.hc.client5.http;

import java.net.IDN;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.hc.core5.util.TextUtils;

/**
* DNS resolver that uses the default OS implementation for resolving host names.
*
Expand All @@ -44,8 +47,18 @@ public class SystemDefaultDnsResolver implements DnsResolver {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
try {
String normalizedHost;
if (TextUtils.isAllASCII(host)) {
normalizedHost = host;
} else {
try {
normalizedHost = IDN.toASCII(host);
} catch (final IllegalArgumentException e) {
normalizedHost = host; // Fall back to original hostname
}
}
// Try resolving using the default resolver
return InetAddress.getAllByName(host);
return InetAddress.getAllByName(normalizedHost);
} catch (final UnknownHostException e) {
// If default resolver fails, try stripping the IPv6 zone ID and resolving again
String strippedHost = null;
Expand Down

0 comments on commit 3c78786

Please sign in to comment.