Skip to content

Commit

Permalink
Attempt to recover from an UnknownHostException. If getLocalHost()
Browse files Browse the repository at this point in the history
throws an exception, attempt to provide the IP address instead.  This
is useful on those systems without a hostname explicitly defined.
  • Loading branch information
timclemons authored and ceharris committed Apr 18, 2013
1 parent 97922ee commit a24b423
Showing 1 changed file with 28 additions and 2 deletions.
Expand Up @@ -14,6 +14,8 @@
package ch.qos.logback.core.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.List;
Expand All @@ -30,8 +32,32 @@ public ContextUtil(Context context) {
}

public static String getLocalHostName() throws UnknownHostException {
InetAddress localhost = InetAddress.getLocalHost();
return localhost.getHostName();
try {
InetAddress localhost = InetAddress.getLocalHost();
return localhost.getHostName();
} catch (UnknownHostException e) {
String ipAddress = getLocalAddressAsString();
if (ipAddress == null) {
throw e;
}
return ipAddress;
}
}

private static String getLocalAddressAsString() {
try {
NetworkInterface networkInterface = NetworkInterface.getNetworkInterfaces().nextElement();
if (networkInterface == null) {
return null;
}
InetAddress ipAddress = networkInterface.getInetAddresses().nextElement();
if (ipAddress == null) {
return null;
}
return ipAddress.getHostAddress();
} catch (SocketException e) {
return null;
}
}

/**
Expand Down

0 comments on commit a24b423

Please sign in to comment.