public class DNSQuery {
public static void main(String[] args) throws NamingException {
System.setProperty("socksProxyHost", "proxy2.lh.petrochina");
System.setProperty("socksProxyPort", "8080");
//域名和DNS服务器
String domain = args[0];
String dnsServer = args.length<2?"":"//"+args[1];
Hashtable<String,String> env = new Hashtable<String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
env.put(Context.PROVIDER_URL, "dns:"+dnsServer);
DirContext dirContext = new InitialDirContext(env);
//分别获取所有属性和带有MX的属性
Attributes allAttribute = dirContext.getAttributes(domain);
Attributes mxAttribute = dirContext.getAttributes(domain,new String[]{"MX"});
//让自动选择
/*
DirContext dirContext = new InitialDirContext();
Attributes allAttribute = dirContext.getAttributes("dns:"+dnsServer+"/"+domain);
Attributes mxAttribute = dirContext.getAttributes("dns:"+dnsServer+"/"+domain,
new String[]{"MX"});*/
System.out.println("打印出域 "+domain + " 中的所有Attributes对象");
System.out.println(allAttribute);
System.out.println("打印出域 "+domain + " 中的只含有mx的Attributes对象");
System.out.println(mxAttribute);
System.out.println("打印Attributes的属性");
NamingEnumeration ne = allAttribute.getAll();
while (ne.hasMoreElements()) {
System.out.println(ne.next());
}
System.out.println("直接检索");
Attribute attribute = allAttribute.get("MX");
System.out.println(attribute);
System.out.println("mx的第一个属性");
String record = (String) attribute.get();
System.out.println(record);
System.out.println("提取服务器地址");
String smtp = record.substring(record.indexOf(" ") + 1);
System.out.println(smtp);
}
}