Alex Rivera | Logout

Need to perform a reverse DNS lookup of a particular IP address in java

Asked 2011-08-17T18:26:55.237
12

I need to get the DNS address, for example "http://stackoverflow.com/questions/ask". I used the following code and able to get in the form of 192.X.X.X.

  Hashtable env = new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
  DirContext ictx = new InitialDirContext(env);
  String dnsServers = (String) ictx.getEnvironment().get("java.naming.provider.url");

  System.out.println("DNS Servers: " + dnsServers ); 
Edit
Report

2 Answers

19
InetAddress ia = InetAddress.getByAddress(new byte[] {74,125,127,106});
// or 
ia = InetAddress.getByName("74.125.127.106");
System.out.println(ia.getCanonicalHostName());
answered 2011-08-17T18:48:07.583
8

CodingForums similar question -- see post #5 (DISCLAIMER: Code is not mine, not tested by me)


Code from linked source:

/**
 * 25 Nov 2009 REVERSE DNS LOOKUP USING JNDI
 * In this example the IP being looked up is 211.21.152.4
 * The octets are reversed (4.152.21.211)
 * and appended to the in-addr.arpa zone:
 * 4.152.21.211.in-addr.arpa
 */

import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;

public class dns    { 
    public static void main(String[] args)  { 
        try {
            Hashtable env = new Hashtable();
            env.put("java.naming.factory.initial","com.sun.jndi.dns.DnsContextFactory");

            DirContext ctx = new InitialDirContext(env);
            Attributes attrs = ctx.getAttributes("4.152.21.211.in-addr.arpa",new String[] {"PTR"});

            for (NamingEnumeration ae = attrs.getAll();ae.hasMoreElements();) {
                Attribute attr = (Attribute)ae.next();
                String attrId = attr.getID();
                for (Enumeration vals = attr.getAll();vals.hasMoreElements();
                System.out.println(attrId + ": " + vals.nextElement()));
            }

            ctx.close();
        }   

        catch(Exception e) {
            System.out.println("NO REVERSE DNS");
        }
    }
}
answered 2011-08-17T18:41:00.510

Your Answer