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