Skip to content

Commit

Permalink
Use hostname on macOS to lookup local host name
Browse files Browse the repository at this point in the history
This is to work around a five second lag when using the JDK approach, see https://bugs.openjdk.java.net/browse/JDK-8143378.
  • Loading branch information
lptr committed Oct 28, 2019
1 parent 344b0fb commit ea7879e
Showing 1 changed file with 35 additions and 7 deletions.
Expand Up @@ -15,10 +15,13 @@
*/
package org.gradle.internal.remote.internal.inet;

import org.gradle.internal.os.OperatingSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
Expand All @@ -38,16 +41,41 @@ public class InetAddressFactory {
private String hostName;

public String getHostname() {
synchronized (lock) {
if (hostName == null) {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
hostName = getCommunicationAddresses().get(0).toString();
if (hostName == null) {
synchronized (lock) {
// Work around https://bugs.openjdk.java.net/browse/JDK-8143378 on macOS
// See also https://stackoverflow.com/a/39698914
if (hostName == null && OperatingSystem.current() == OperatingSystem.MAC_OS) {
ProcessBuilder builder = new ProcessBuilder("hostname");
try {
Process process = builder.start();
int result = process.waitFor();
if (result == 0) {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
String line = reader.readLine();
if (line != null) {
hostName = line;
}
} finally {
reader.close();
}
}
} catch (Exception e) {
logger.debug("Couldn't resolve hostname by running hostname, falling back to using JDK", e);
}
}

if (hostName == null) {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
hostName = getCommunicationAddresses().get(0).toString();
}
}
}
return hostName;
}
return hostName;
}

/**
Expand Down

0 comments on commit ea7879e

Please sign in to comment.