- 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(SMTP.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);
- InetAddress ia = InetAddress.getByName(mx);
- if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
- ret[i++] = ia;
- }
- }
- } catch (Exception e) {
- Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
- Log.warn(SMTP.class, e);
- return new InetAddress[0];
- }
- return ret;
- }