2009-10-22 75 views
3

DNS查找。如果我從一個DNS名稱來查找一個IP地址如下:獲取域名服務器信息在Java

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

我可以找出哪些域名服務器給我的信息?

回答

2

我不知道這是否是你想要的,但有一個DNSJava庫,提供了Java中的DNS功能。也許你可以用它來更好地理解你的問題,或者實現一個特定的解決方案?就像我說的,對你來說不是一個完美的搭配,但也許有幫助。

2

對於一個給定的InetAddress,請嘗試以下操作:

// 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(); 

適應它拿起你在找什麼。

+0

對我沒有效果。我剛剛獲得了A記錄,沒有其他屬性。也許是環保的事情。 – Brabster 2010-01-12 22:21:35

+0

那麼,* A記錄爲您提供了域*的IP地址。這不正是你所要求的嗎? – 2010-01-12 22:37:15

0

您需要一個命名上下文。可選,您可以指定DNS服務器。 即使你需要選擇你正在尋找的。這是一個例子。

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