JAva DNSドメイン名解析

4631 ワード

依存パッケージ:

    dnsjava
    dnsjava
    2.1.8
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xbill.DNS.*;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.util.*;

/**
 * @author xxy
 */
public class DnsUtils {
    private static final Logger log = LoggerFactory.getLogger(DnsUtils.class);

    public static void main(String[] args) {
        String[] ipArray = {"156.238.169.163"};
        List list = Arrays.asList(ipArray);
        Set set = getDnsRealIp(list,"fig.cdn.com");
        Iterator it = set.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }

    /**
     *   DNS     (   )
     *
     * @param domain     DNS     
     * @param provider      DNS   
     * @param types        "A"(IP  ),"MX"
     * @param timeout     
     * @param retryCount        
     *
     * @return          
     *
     * @throws NamingException
     *
     */

    @SuppressWarnings("rawtypes" )
    public static ArrayList getDNSRecs(String domain, String provider,
                                               String [] types, int timeout, int retryCount) throws NamingException {

        ArrayList results = new ArrayList(15);

        Hashtable env = new Hashtable();

        env.put( "java.naming.factory.initial" ,
                "com.sun.jndi.dns.DnsContextFactory" );

        //       
        env.put(Context. PROVIDER_URL, "dns://" + provider);

        //     
        env.put( "com.sun.jndi.dns.timeout.initial" , String.valueOf(timeout));

        //     
        env.put( "com.sun.jndi.dns.timeout.retries" , String.valueOf(retryCount));

        DirContext ictx = new InitialDirContext(env);
        Attributes attrs = ictx.getAttributes(domain, types);

        for (Enumeration e = attrs.getAll(); e.hasMoreElements();) {
            Attribute a = (Attribute) e.nextElement();
            int size = a.size();
            for (int i = 0; i < size; i++) {
                results.add((String) a.get(i));
            }
        }
        return results;
    }

    /**
     *       IP(   )
     * @param domain    
     * @param dnsServers    DNS     
     * @param timeout     
     * @param retryCount        
     * @return
     */
    public static Set getAllIP(String domain, String[] dnsServers,
                                       int timeout, int retryCount) {
        Set ips = new HashSet();

        for(String dnsServer: dnsServers) {
            List ipList;
            try {
                ipList = getDNSRecs(domain, dnsServer, new String[]{"A"},
                        timeout, retryCount);
            } catch (NamingException e) {
                continue;
            }
            ips.addAll(ipList);
        }

        return ips;
    }

    /**
     *       IP(  ,       )
     * @param ipList dns     IP
     * @param dnsServerName dns    
     * @return
     */
    public static Set getDnsRealIp(List ipList,String dnsServerName){
        Set set = new HashSet<>();
        try {
            log.info("getDnsRealIp ipList==========>{}",ipList);
            for(String ip : ipList) {
                Resolver resolver = new SimpleResolver(ip);
                Lookup lookup = new Lookup(dnsServerName, Type.A);
                lookup.setResolver(resolver);
                Cache cache = new Cache();
                lookup.setCache(cache);
                lookup.run();
                if (lookup.getResult() == Lookup.SUCCESSFUL) {
                    Record[] records = lookup.getAnswers();
                    for (Record record : records) {
                        log.info("getDnsRealIp  ip->{}, dsn-->{}",ip,record.toString());
                        set.add(record.rdataToString());
                    }
                }
            }
        }catch (Exception e){
            log.info("getDnsRealIp error=====>",e);
        }
        return set;
    }
}