how do you get the default DNS server? It is a major hassle getting
customers to configure their DNS servers, which may change.
I am used to doing it this way:
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
env.put("java.naming.provider.url", "dns://" + dns + "/");
<etc>
which, as you mention, requires the DNS to be known.
However, the following code was posted here recently and requires no
DNS hardcoded. I awalys thought the naming provider was required.
Apologies to the author for not finding the attribution:
import java.util.Hashtable;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class MXLookup {
public static void main( String args[] ) {
if( args.length == 0 ) {
System.err.println( "Usage: MXLookup host [...]" );
System.exit( 12 );
}
for( int i = 0; i < args.length; i++ ) {
try {
System.out.println( args
+ " has " +
doLookup( args ) + " mail servers" );
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
static int doLookup( String hostName ) throws NamingException {
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext( env );
Attributes attrs = ictx.getAttributes( hostName,
new String[] { "MX" });
Attribute attr = attrs.get( "MX" );
if( attr == null )
return( 0 );
return( attr.size() );
}
}