开发者

Obtain nameserver information for DNS lookups in Java

If I look up a IP 开发者_如何学JAVAaddress 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?


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.


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.


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜