5 import org.ibex.util.*;
7 import org.xbill.DNS.*;
8 import org.xbill.DNS.Message;
10 import javax.naming.directory.*;
12 public class DNSUtil {
14 public static String reverseLookup(InetAddress ip) throws IOException {
15 Resolver res = new ExtendedResolver();
17 res.send(Message.newQuery(Record.newRecord(ReverseMap.fromAddress(ip), Type.PTR, DClass.IN)));
18 Record[] answers = response.getSectionArray(Section.ANSWER);
19 return answers.length==0 ? null : answers[0].rdataToString();
22 public static InetAddress[] getMailExchangerIPs(String hostName) {
25 Hashtable env = new Hashtable();
26 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
27 DirContext ictx = new InitialDirContext(env);
28 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
29 Attribute attr = attrs.get("MX");
31 ret = new InetAddress[1];
33 ret[0] = InetAddress.getByName(hostName);
34 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
36 } catch (UnknownHostException uhe) {
37 Log.warn(DNSUtil.class, "no MX hosts or A record for " + hostName);
38 return new InetAddress[0];
41 ret = new InetAddress[attr.size()];
42 NamingEnumeration ne = attr.getAll();
43 for(int i=0; ne.hasMore();) {
44 String mx = (String)ne.next();
45 // FIXME we should be sorting here
46 mx = mx.substring(mx.indexOf(" ") + 1);
47 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
48 InetAddress ia = InetAddress.getByName(mx);
49 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
53 } catch (Exception e) {
54 Log.warn(DNSUtil.class, "couldn't find MX host for " + hostName + " due to");
55 Log.warn(DNSUtil.class, e);
56 return new InetAddress[0];