Java DNS 解析問題 ... 請高手幫忙 !! 机器名?dns的结果是一个ip地址,机器名是可选的,所以不一定能够成功,况且机器名对于远程访问没有用处阿。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 比如, sohu.com 是一個域名, 但是 www.sohu.com 是 sohu.com 域下的 Web 服務器 sohumx.sohu.com 是 sohu.com 域下的 mail 服務器 .那麼, 現在我知道一個郵件地址 [email protected] . 我就需要知道 sohu.com 域下的 mail 服務器的名稱, 才能夠連接 .這些 服務器名是需要在 dns 中設定的, 但是, 我不知道 java 中可否直接從 DNS Server 獲得 sohu.com 的 mail 服務器的名稱 ? http://www.xbill.org/dnsjava我用过。自己去查查吧。 /* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE file. */package org.apache.james.dnsserver;import org.apache.avalon.framework.activity.Initializable;import org.apache.avalon.framework.configuration.Configurable;import org.apache.avalon.framework.configuration.Configuration;import org.apache.avalon.framework.configuration.ConfigurationException;import org.apache.avalon.framework.logger.AbstractLogEnabled;import org.apache.avalon.phoenix.Block;import org.xbill.DNS.*;import java.net.InetAddress;import java.net.UnknownHostException;import java.util.*;/** * @version 1.0.0, 18/06/2000 * @author Serge Knystautas <[email protected]> */public class DNSServer extends AbstractLogEnabled implements Block, Configurable, Initializable, org.apache.james.services.DNSServer { private Resolver resolver; private Cache cache; private byte dnsCredibility; private Collection servers = new Vector(); public void configure( final Configuration configuration ) throws ConfigurationException { // Get this servers that this block will use for lookups final Configuration serversConfiguration = configuration.getChild( "servers" ); final Configuration[] serverConfigurations = serversConfiguration.getChildren( "server" ); for ( int i = 0; i < serverConfigurations.length; i++ ) { servers.add( serverConfigurations[ i ].getValue() ); } final boolean authoritative = configuration.getChild( "authoritative" ).getValueAsBoolean( false ); dnsCredibility = authoritative ? Credibility.AUTH_ANSWER : Credibility.NONAUTH_ANSWER; } public void initialize() throws Exception { getLogger().info("DNSServer init..."); if (servers.isEmpty()) { try { servers.add( InetAddress.getLocalHost().getHostName() ); } catch ( UnknownHostException ue ) { servers.add( "127.0.0.1" ); } } for (Iterator i = servers.iterator(); i.hasNext(); ) { getLogger().info("DNS Servers is: " + i.next()); } //Create the extended resolver... final String serversArray[] = (String[])servers.toArray(new String[0]); resolver = new ExtendedResolver( serversArray ); cache = new Cache (DClass.IN); getLogger().info("DNSServer ...init end"); } public Collection findMXRecords(String hostname) { Record answers[] = lookup(hostname, Type.MX); Collection servers = new Vector (); try { if (answers == null) { return servers; } MXRecord mxAnswers[] = new MXRecord[answers.length]; for (int i = 0; i < answers.length; i++) { mxAnswers[i] = (MXRecord)answers[i]; } Comparator prioritySort = new Comparator () { public int compare (Object a, Object b) { MXRecord ma = (MXRecord)a; MXRecord mb = (MXRecord)b; return ma.getPriority () - mb.getPriority (); } }; Arrays.sort(mxAnswers, prioritySort); for (int i = 0; i < mxAnswers.length; i++) { servers.add(mxAnswers[i].getTarget ().toString ()); } return servers; } finally { //If we found no results, we'll add the original domain name if //it's a valid DNS entry if (servers.size () == 0) { try { InetAddress.getByName(hostname); servers.add(hostname); } catch (UnknownHostException uhe) { } } } } public Record[] lookup(String name, short type) { return rawDNSLookup(name,false,type); } private Record[] rawDNSLookup(String namestr, boolean querysent, short type) { Name name = new Name(namestr); short dclass = DClass.IN; Record [] answers; int answerCount = 0, n = 0; Enumeration e; SetResponse cached = cache.lookupRecords(name, type, dnsCredibility); if (cached.isSuccessful()) { RRset [] rrsets = cached.answers(); answerCount = 0; for (int i = 0; i < rrsets.length; i++) { answerCount += rrsets[i].size(); } answers = new Record[answerCount]; for (int i = 0; i < rrsets.length; i++) { e = rrsets[i].rrs(); while (e.hasMoreElements()) { Record r = (Record)e.nextElement(); answers[n++] = r; } } } else if (cached.isNXDOMAIN() || cached.isNXRRSET()) { return null; } else if (querysent) { return null; } else { Record question = Record.newRecord(name, type, dclass); org.xbill.DNS.Message query = org.xbill.DNS.Message.newQuery(question); org.xbill.DNS.Message response; try { response = resolver.send(query); } catch (Exception ex) { return null; } short rcode = response.getHeader().getRcode(); if (rcode == Rcode.NOERROR || rcode == Rcode.NXDOMAIN) { cache.addMessage(response); } if (rcode != Rcode.NOERROR) { return null; } return rawDNSLookup(namestr, true, Type.MX); } return answers; }}上面是Jakarta/James的DNSServer的源码,仔细研究一下。 我用过dnsjava,和上面代码有些类似之处:import org.xbill.DNS.*;public class MXLookup { public static String[] lookup(String domain) { Record[] records = dns.getRecords(domain, Type.MX); if (records == null || records.length == 0) return null; //对records按照MX优先级进行排序,优先级高的在前面。 Arrays.sort(records, new Comparator() { public int compare(Object o1, Object o2) { MXRecord r1 = (MXRecord)o1; MXRecord r2 = (MXRecord)o2; return r2.getPriority() - r1.getPropertiy(); } } String [] hosts = new String[records.length]; for (int i=0; i<records.length; i++) hosts[i] = ((MXRecord)records[i]).getTarget().toString(); return hosts; } }使用方法: String[] hosts = MXLookup.lookup("21cn.com");返回的不是IP地址,而是MX主机名。返回的hosts可能是无效的,比如21cn.com返回两个MX记录: mta.21cn.com和 mta2.21cn.com,其中mta.21cn.com连接不上。 protected 不是继承可用么? connection问题 java 求教画图保存问题? 线程的临界区问题? 大家过来看看。如何去掉 一个字符串末尾的带的”,“逗号。郁闷了一天了 socket编程的输入输出流问题(搞分) 请问有没有这种软件 用jb能不能象vb,一样用鼠标一些控件进行界面设置 如何汉化一个java编写的应用程序? Comparator 的一些小问题 这样取得java.sql.Date日期中的年? tomcat配置问题。
但是 www.sohu.com 是 sohu.com 域下的 Web 服務器
sohumx.sohu.com 是 sohu.com 域下的 mail 服務器 .
那麼, 現在我知道一個郵件地址 [email protected] .
我就需要知道 sohu.com 域下的 mail 服務器的名稱, 才能夠連接 .
這些 服務器名是需要在 dns 中設定的,
但是, 我不知道 java 中可否直接從 DNS Server 獲得 sohu.com 的 mail 服務器的名稱 ?
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*/
package org.apache.james.dnsserver;import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.phoenix.Block;
import org.xbill.DNS.*;import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;/**
* @version 1.0.0, 18/06/2000
* @author Serge Knystautas <[email protected]>
*/
public class DNSServer
extends AbstractLogEnabled
implements Block, Configurable, Initializable,
org.apache.james.services.DNSServer { private Resolver resolver;
private Cache cache;
private byte dnsCredibility;
private Collection servers = new Vector(); public void configure( final Configuration configuration )
throws ConfigurationException { // Get this servers that this block will use for lookups
final Configuration serversConfiguration = configuration.getChild( "servers" );
final Configuration[] serverConfigurations =
serversConfiguration.getChildren( "server" ); for ( int i = 0; i < serverConfigurations.length; i++ )
{
servers.add( serverConfigurations[ i ].getValue() );
} final boolean authoritative =
configuration.getChild( "authoritative" ).getValueAsBoolean( false );
dnsCredibility = authoritative ? Credibility.AUTH_ANSWER : Credibility.NONAUTH_ANSWER;
} public void initialize()
throws Exception { getLogger().info("DNSServer init..."); if (servers.isEmpty()) {
try {
servers.add( InetAddress.getLocalHost().getHostName() );
} catch ( UnknownHostException ue ) {
servers.add( "127.0.0.1" );
}
} for (Iterator i = servers.iterator(); i.hasNext(); ) {
getLogger().info("DNS Servers is: " + i.next());
} //Create the extended resolver...
final String serversArray[] = (String[])servers.toArray(new String[0]);
resolver = new ExtendedResolver( serversArray ); cache = new Cache (DClass.IN); getLogger().info("DNSServer ...init end");
} public Collection findMXRecords(String hostname) {
Record answers[] = lookup(hostname, Type.MX); Collection servers = new Vector ();
try {
if (answers == null) {
return servers;
} MXRecord mxAnswers[] = new MXRecord[answers.length];
for (int i = 0; i < answers.length; i++) {
mxAnswers[i] = (MXRecord)answers[i];
} Comparator prioritySort = new Comparator () {
public int compare (Object a, Object b) {
MXRecord ma = (MXRecord)a;
MXRecord mb = (MXRecord)b;
return ma.getPriority () - mb.getPriority ();
}
}; Arrays.sort(mxAnswers, prioritySort); for (int i = 0; i < mxAnswers.length; i++) {
servers.add(mxAnswers[i].getTarget ().toString ());
}
return servers;
} finally {
//If we found no results, we'll add the original domain name if
//it's a valid DNS entry
if (servers.size () == 0) {
try {
InetAddress.getByName(hostname);
servers.add(hostname);
} catch (UnknownHostException uhe) {
}
}
}
} public Record[] lookup(String name, short type) {
return rawDNSLookup(name,false,type);
} private Record[] rawDNSLookup(String namestr, boolean querysent, short type) {
Name name = new Name(namestr);
short dclass = DClass.IN; Record [] answers;
int answerCount = 0, n = 0;
Enumeration e; SetResponse cached = cache.lookupRecords(name, type, dnsCredibility);
if (cached.isSuccessful()) {
RRset [] rrsets = cached.answers();
answerCount = 0;
for (int i = 0; i < rrsets.length; i++) {
answerCount += rrsets[i].size();
} answers = new Record[answerCount]; for (int i = 0; i < rrsets.length; i++) {
e = rrsets[i].rrs();
while (e.hasMoreElements()) {
Record r = (Record)e.nextElement();
answers[n++] = r;
}
}
}
else if (cached.isNXDOMAIN() || cached.isNXRRSET()) {
return null;
}
else if (querysent) {
return null;
}
else {
Record question = Record.newRecord(name, type, dclass);
org.xbill.DNS.Message query = org.xbill.DNS.Message.newQuery(question);
org.xbill.DNS.Message response; try {
response = resolver.send(query);
}
catch (Exception ex) {
return null;
} short rcode = response.getHeader().getRcode();
if (rcode == Rcode.NOERROR || rcode == Rcode.NXDOMAIN) {
cache.addMessage(response);
} if (rcode != Rcode.NOERROR) {
return null;
} return rawDNSLookup(namestr, true, Type.MX);
} return answers;
}
}
上面是Jakarta/James的DNSServer的源码,仔细研究一下。
Record[] records = dns.getRecords(domain, Type.MX);
if (records == null || records.length == 0) return null; //对records按照MX优先级进行排序,优先级高的在前面。
Arrays.sort(records, new Comparator() {
public int compare(Object o1, Object o2) {
MXRecord r1 = (MXRecord)o1;
MXRecord r2 = (MXRecord)o2;
return r2.getPriority() - r1.getPropertiy();
}
}
String [] hosts = new String[records.length];
for (int i=0; i<records.length; i++)
hosts[i] = ((MXRecord)records[i]).getTarget().toString();
return hosts;
}
}使用方法:
String[] hosts = MXLookup.lookup("21cn.com");返回的不是IP地址,而是MX主机名。返回的hosts可能是无效的,比如21cn.com返回两个MX记录:
mta.21cn.com和
mta2.21cn.com,其中mta.21cn.com连接不上。