X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=src%2Forg%2Fibex%2Fmail%2FDNSUtil.java;h=403ff1a732e8ea14b40b040e25957191075e192a;hb=4b76a31e8f86bc8de673899bbb45252c01e9a0f6;hp=7ad56c8665a5cc722bd1fc68e2d4c48beffd5f03;hpb=4167fdf3a0e9239d41852f9d5bca142edb4f5e81;p=org.ibex.mail.git diff --git a/src/org/ibex/mail/DNSUtil.java b/src/org/ibex/mail/DNSUtil.java index 7ad56c8..403ff1a 100644 --- a/src/org/ibex/mail/DNSUtil.java +++ b/src/org/ibex/mail/DNSUtil.java @@ -2,9 +2,16 @@ package org.ibex.mail; import java.io.*; import java.util.*; import java.net.*; +import org.ibex.util.*; +import org.ibex.net.*; import org.xbill.DNS.*; import org.xbill.DNS.Message; +import javax.naming.*; +import javax.naming.directory.*; + +// FEATURE: use DNSJava for reverse lookups? +// FEATURE: investigate other cool stuff in DNSJava we can use public class DNSUtil { public static String reverseLookup(InetAddress ip) throws IOException { @@ -15,4 +22,47 @@ public class DNSUtil { return answers.length==0 ? null : answers[0].rdataToString(); } + public static InetAddress[] getMailExchangerIPs(String hostName) { + InetAddress[] ret; + try { + 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) { + ret = new InetAddress[1]; + try { + ret[0] = InetAddress.getByName(hostName); + if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException(); + return ret; + } catch (UnknownHostException uhe) { + Log.warn(DNSUtil.class, "no MX hosts or A record for " + hostName); + return new InetAddress[0]; + } + } else { + ret = new InetAddress[attr.size()]; + NamingEnumeration ne = attr.getAll(); + for(int i=0; ne.hasMore();) { + String mx = (String)ne.next(); + // FIXME we should be sorting here + mx = mx.substring(mx.indexOf(" ") + 1); + if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1); + try { + InetAddress ia = InetAddress.getByName(mx); + if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue; + ret[i++] = ia; + } catch (Exception e) { + Log.info("safe to ignore", e); + } + } + } + } catch (Exception e) { + Log.warn(DNSUtil.class, "couldn't find MX host for " + hostName + " due to"); + Log.warn(DNSUtil.class, e); + return new InetAddress[0]; + } + return ret; + } + }