Advertisement
tahg

Untitled

Apr 24th, 2017
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. private static String getHostName(final String ip) {
  2. String retVal = null;
  3. // System.out.println(ip);
  4. final String[] bytes = ip.split("\\.");
  5. if (bytes.length == 4) {
  6. try {
  7. final java.util.Hashtable<String, String> env = new java.util.Hashtable<String, String>();
  8. env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
  9. final javax.naming.directory.DirContext ctx = new javax.naming.directory.InitialDirContext(env);
  10. final String reverseDnsDomain = bytes[3] + "." + bytes[2] + "." + bytes[1] + "." + bytes[0]
  11. + ".in-addr.arpa";
  12. final javax.naming.directory.Attributes attrs = ctx.getAttributes(reverseDnsDomain,
  13. new String[] { "PTR", });
  14. for (final javax.naming.NamingEnumeration<? extends javax.naming.directory.Attribute> ae = attrs
  15. .getAll(); ae.hasMoreElements();) {
  16. final javax.naming.directory.Attribute attr = ae.next();
  17. final String attrId = attr.getID();
  18. for (final java.util.Enumeration<?> vals = attr.getAll(); vals.hasMoreElements();) {
  19. String value = vals.nextElement().toString();
  20. // System.out.println(attrId + ": " + value);
  21.  
  22. if ("PTR".equals(attrId)) {
  23. // System.out.println(value);
  24. final int len = value.length();
  25. if (value.charAt(len - 1) == '.') {
  26. // Strip out trailing period
  27. value = value.substring(0, len - 1);
  28. }
  29. retVal = value;
  30. }
  31. }
  32. }
  33. ctx.close();
  34. } catch (final javax.naming.NamingException e) {
  35. // No reverse DNS that we could find, try with InetAddress
  36. System.out.print(""); // NO-OP
  37. }
  38. }
  39.  
  40. if (null == retVal) {
  41. try {
  42. retVal = java.net.InetAddress.getByName(ip).getCanonicalHostName();
  43. } catch (final java.net.UnknownHostException e1) {
  44. retVal = ip;
  45. }
  46. }
  47.  
  48. return retVal;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement