Skip to content

Instantly share code, notes, and snippets.

@nickgrealy
Last active May 12, 2016 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickgrealy/07698367d2e64740bd56b08fa9fa95e0 to your computer and use it in GitHub Desktop.
Save nickgrealy/07698367d2e64740bd56b08fa9fa95e0 to your computer and use it in GitHub Desktop.
Utility class for doing DNS reverse lookups, without the fluff.
import sun.net.spi.nameservice.NameService;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;
/**
* Utility class for doing DNS reverse lookups, without the fluff.
*/
public class InetAddressUtils {
public static List<NameService> nameServices;
static {
// load name services once on initialisation...
nameServices = getNameServices();
}
@SuppressWarnings("unchecked")
public static List<NameService> getNameServices() {
try {
// do naughty things...
Field staticField = InetAddress.class.getDeclaredField("nameServices");
staticField.setAccessible(true);
return (List<NameService>) staticField.get(null);
} catch (Throwable t) {
throw new RuntimeException("Got caught doing naughty things.", t);
}
}
/**
* <p>
* {@link InetAddress#getHostAddress()}'s implementation does a few additional checks which I don't want (or which
* may not be supported in my system e.g. forward DNS lookups). So here's an implementation that JUST get's the
* hostname (i.e. performs a reverse DNS lookup).
* </p>
* <p>
* Unfortunately, everything in `java.net` is locked down like a mofo, so we have to do some "naughty" things,
* to go places that we're not supposed to go.
* </p>
*/
public static String getHostName(InetAddress addr) {
String host = null;
for (NameService nameService : nameServices) {
try {
host = nameService.getHostByAddr(addr.getAddress());
} catch (Throwable t) {
// NOOP: problem getting hostname from this name service, continue looping...
}
}
return host != null ? host : addr.getHostAddress();
}
/**
* Set's the accessiblity on an object.
*/
static void setAccessible(final AccessibleObject ao,
final boolean accessible) {
if (System.getSecurityManager() == null)
ao.setAccessible(accessible);
else {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ao.setAccessible(accessible);
return null;
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment