brabster
brabster

Reputation: 43560

Obtain nameserver information for DNS lookups in Java

If I look up a IP address from a DNS name as follows:

InetAddress inetAddress = InetAddress.getByName(name);
String address = inetAddress.getHostAddress();

Can I find out which nameserver gave me the information?

Upvotes: 4

Views: 5990

Answers (3)

SkateScout
SkateScout

Reputation: 870

you need an Naming Context. Optional you can Specify the DNS Server. And even then you need to select that you are looking for. Here is an example.

final String ADDR_ATTRIB = "A";
final String[] ADDR_ATTRIBS = {ADDR_ATTRIB};
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
idc = new InitialDirContext(env);
env.put(Context.PROVIDER_URL, "dns://"+dnsServer);
final List<String> ipAddresses = new LinkedList<>();
final Attributes attrs = idc.getAttributes(hostname, ADDR_ATTRIBS);
final Attribute attr = attrs.get(ADDR_ATTRIB);
if (attr != null) for (int i = 0; i < attr.size(); i++)  ipAddresses.add((String) attr.get(i));

Upvotes: 0

Pascal Thivent
Pascal Thivent

Reputation: 570285

For a given InetAddress, try the following:

// get the default initial Directory Context
InitialDirContext idc = new InitialDirContext();
// get the DNS records for inetAddress
Attributes attributes = idc.getAttributes("dns:/" + inetAddress.getHostName());
// get an enumeration of the attributes and print them out
NamingEnumeration attributeEnumeration = attributes.getAll();
System.out.println("-- DNS INFORMATION --");
while (attributeEnumeration.hasMore()) {
    System.out.println("" + attributeEnumeration.next());
}
attributeEnumeration.close();

Adapt it to pick up what you're looking for.

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272207

I'm not sure if this is what you want, but there's a DNSJava library which provides DNS functionality in Java. Perhaps you can use this to either get a better understanding of your issues, or to implement a particular solution ? Like I say, not a perfect match for you, but perhaps helpful.

Upvotes: 3

Related Questions