类org.xbill.DNS.Lookup源码实例Demo

下面列出了怎么用org.xbill.DNS.Lookup的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: entrada   文件: GoogleResolverCheck.java
@Override
protected List<String> fetch() {

  try {
    Resolver resolver = new SimpleResolver();
    // dns resolvers may take a long time to return a response.
    resolver.setTimeout(timeout);
    Lookup l =
        new Lookup(StringUtils.endsWith(hostname, ".") ? hostname : hostname + ".", Type.TXT);
    // always make sure the cache is empty
    l.setCache(new Cache());
    l.setResolver(resolver);
    Record[] records = l.run();
    if (records != null && records.length > 0) {
      return parse(records[0]);
    }
  } catch (Exception e) {
    log.error("Problem while adding Google resolvers, continue without", e);
  }

  log.error("No Google resolver addresses found");
  return Collections.emptyList();
}
 
源代码2 项目: james-project   文件: DNSJavaServiceTest.java
@Before
public void setUp() throws Exception {
    dnsServer = new TestableDNSServer();

    dnsServer.configure(FileConfigurationProvider.getConfig(new ByteArrayInputStream(DNS_SERVER_CONFIG)));
    dnsServer.init();

    defaultCache = Lookup.getDefaultCache(DClass.IN);
    defaultResolver = Lookup.getDefaultResolver();
    defaultSearchPaths = Lookup.getDefaultSearchPath();
    Lookup.setDefaultCache(null, DClass.IN);
    Lookup.setDefaultResolver(null);
    Lookup.setDefaultSearchPath(new Name[]{});

    dnsServer.setResolver(null);
    mockedCache = mock(Cache.class);
}
 
源代码3 项目: dns-java   文件: XBillDnsSrvResolver.java
@Override
public List<LookupResult> resolve(final String fqdn) {
  Lookup lookup = lookupFactory.forName(fqdn);
  Record[] queryResult = lookup.run();

  switch (lookup.getResult()) {
    case Lookup.SUCCESSFUL:
      return toLookupResults(queryResult);
    case Lookup.HOST_NOT_FOUND:
      // fallthrough
    case Lookup.TYPE_NOT_FOUND:
      LOG.warn("No results returned for query '{}'; result from XBill: {} - {}",
          fqdn, lookup.getResult(), lookup.getErrorString());
      return ImmutableList.of();
    default:
      throw new DnsException(
          String.format("Lookup of '%s' failed with code: %d - %s ",
              fqdn, lookup.getResult(), lookup.getErrorString()));
  }
}
 
源代码4 项目: mireka   文件: MxLookupTest.java
@Test()
public void testNoMxRecords() throws MxLookupException {
    new Expectations() {
        {
            lookup.run();
            result = null;

            lookup.getResult();
            result = Lookup.TYPE_NOT_FOUND;
        }

    };

    Name[] targets = mxLookup.queryMxTargets(EXAMPLE_COM_DOMAIN);
    assertArrayEquals(new Name[] { EXAMPLE_COM_NAME }, targets);
}
 
源代码5 项目: mireka   文件: AddressLookupTest.java
@Test
public void testTransientDnsFailure() {
    new Expectations() {
        {
            lookup.run();
            result = null;

            lookup.getResult();
            result = Lookup.TRY_AGAIN;
        }
    };

    SendException e;
    try {
        addressLookup.queryAddresses(HOST1_EXAMPLE_COM_NAME);
        fail("An exception must have been thrown.");
        return;
    } catch (SendException e1) {
        e = e1;
    }

    assertTrue(e.errorStatus().shouldRetry());
}
 
源代码6 项目: KinoCast   文件: CustomDns.java
private void init() {
    if (mInitialized) return; else mInitialized = true;

    try {
        // configure the resolvers, starting with the default ones (based on the current network connection)
        Resolver defaultResolver = Lookup.getDefaultResolver();
        // use Google's public DNS services
        Resolver googleFirstResolver = new SimpleResolver("8.8.8.8");
        Resolver googleSecondResolver = new SimpleResolver("8.8.4.4");
        // also try using Amazon
        Resolver amazonResolver = new SimpleResolver("205.251.198.30");
        Lookup.setDefaultResolver(new ExtendedResolver(new Resolver[]{
                googleFirstResolver, googleSecondResolver, amazonResolver, defaultResolver }));
    } catch (UnknownHostException e) {
        Log.w(TAG, "Couldn't initialize custom resolvers");
    }
}
 
源代码7 项目: dnsjava   文件: lookup.java
public static void printAnswer(String name, Lookup lookup) {
  System.out.print(name + ":");
  int result = lookup.getResult();
  if (result != Lookup.SUCCESSFUL) {
    System.out.print(" " + lookup.getErrorString());
  }
  System.out.println();
  Name[] aliases = lookup.getAliases();
  if (aliases.length > 0) {
    System.out.print("# aliases: ");
    for (int i = 0; i < aliases.length; i++) {
      System.out.print(aliases[i]);
      if (i < aliases.length - 1) {
        System.out.print(" ");
      }
    }
    System.out.println();
  }
  if (lookup.getResult() == Lookup.SUCCESSFUL) {
    Record[] answers = lookup.getAnswers();
    for (Record answer : answers) {
      System.out.println(answer);
    }
  }
}
 
源代码8 项目: dnsjava   文件: lookup.java
public static void main(String[] args) throws Exception {
  int type = Type.A;
  int start = 0;
  if (args.length > 2 && args[0].equals("-t")) {
    type = Type.value(args[1]);
    if (type < 0) {
      throw new IllegalArgumentException("invalid type");
    }
    start = 2;
  }
  for (int i = start; i < args.length; i++) {
    Lookup l = new Lookup(args[i], type);
    l.run();
    printAnswer(args[i], l);
  }
}
 
源代码9 项目: yeti   文件: ForwardLookupHelper.java
public static List<ForwardLookupResult> getARecord(String hostName, String domainName) throws TextParseException {
    List<ForwardLookupResult> entries = null;
    if (hostName != null && !hostName.isEmpty() && domainName != null && !domainName.isEmpty()) {
        Record[] recs = new Lookup(hostName, Type.A).run();
        if (recs != null) {
            if (recs.length > 0) {
                entries = new ArrayList<>();
                for (Record record : recs) {
                    ForwardLookupResult foundSubDomain = new ForwardLookupResult(domainName);
                    foundSubDomain.setHostName(hostName);
                    String ipAddress = ((ARecord) record).getAddress().getHostAddress();
                    foundSubDomain.setIpAddress(ipAddress);
                    foundSubDomain.setLookupType("A");
                    entries.add(foundSubDomain);
                }
            }
        }
    }
    return entries;
}
 
源代码10 项目: yeti   文件: ForwardLookupHelper.java
public static List<ForwardLookupResult> getAAAARecord(String hostName, String domainName) throws TextParseException {
    List<ForwardLookupResult> entries = null;
    if (hostName != null && !hostName.isEmpty() && domainName != null && !domainName.isEmpty()) {
        Record[] recs = new Lookup(hostName, Type.AAAA).run();
        if (recs != null) {
            if (recs.length > 0) {
                entries = new ArrayList<>();
                for (Record record : recs) {
                    ForwardLookupResult foundSubDomain = new ForwardLookupResult(domainName);
                    foundSubDomain.setHostName(hostName);
                    String ipAddress = ((AAAARecord) record).getAddress().getHostAddress();
                    foundSubDomain.setIpAddress(ipAddress);
                    foundSubDomain.setLookupType("A");
                    entries.add(foundSubDomain);
                }
            }
        }
    }
    return entries;
}
 
源代码11 项目: yeti   文件: DNS.java
public static List<ARecordResult> getARecord(String hostName) throws TextParseException {
    List<ARecordResult> entries = null;

    Record[] recs = new Lookup(hostName, Type.A).run();
    if (recs != null) {
        if (recs.length > 0) {
            entries = new ArrayList<>();
            for (Record record : recs) {
                ARecordResult foundSubDomain = new ARecordResult(NetworkTools.getDomainFromHost(hostName));
                foundSubDomain.setHostName(hostName);
                String ipAddress = ((ARecord) record).getAddress().getHostAddress();
                foundSubDomain.setIpAddress(ipAddress);
                foundSubDomain.setLookupType("A");
                entries.add(foundSubDomain);
            }
        }
    }

    return entries;
}
 
源代码12 项目: yeti   文件: NetworkTools.java
public static String getDomainFromHost(String host) {
    String tmpHost = host;
    if (host.isEmpty()) {
        return "";
    }
    while (true) {
        try {
            if (!tmpHost.startsWith("www.")) {
                Record[] recs = new Lookup(tmpHost, Type.SOA).run();
                if (recs != null) {
                    return tmpHost;
                }
            }
            if (tmpHost.contains(".")) {
                tmpHost = tmpHost.split("\\.", 2)[1];
            } else {
                break;
            }
        } catch (TextParseException ex) {
            Logger.getLogger("networkTools.getDomainFromHost").log(Level.SEVERE, null, ex);
            break;
        }
    }
    return "";
}
 
源代码13 项目: yeti   文件: DataAPI.java
public List<ARecordResult> getARecord(String hostName) throws TextParseException {
    List<ARecordResult> entries = null;

    Record[] recs = new Lookup(hostName, Type.A).run();
    if (recs != null) {
        if (recs.length > 0) {
            entries = new ArrayList<>();
            for (Record record : recs) {
                ARecordResult foundSubDomain = new ARecordResult(NetworkTools.getDomainFromHost(hostName));
                foundSubDomain.setHostName(hostName);
                String ipAddress = ((ARecord) record).getAddress().getHostAddress();
                foundSubDomain.setIpAddress(ipAddress);
                foundSubDomain.setLookupType("A");
                entries.add(foundSubDomain);
            }
        }
    }

    return entries;
}
 
源代码14 项目: open-rmbt   文件: Helperfunctions.java
public static String reverseDNSLookup(final InetAddress adr)
{
    try
    {
        final Name name = ReverseMap.fromAddress(adr);
        
        final Lookup lookup = new Lookup(name, Type.PTR);
        lookup.setResolver(new SimpleResolver());
        lookup.setCache(null);
        final Record[] records = lookup.run();
        if (lookup.getResult() == Lookup.SUCCESSFUL)
            for (final Record record : records)
                if (record instanceof PTRRecord)
                {
                    final PTRRecord ptr = (PTRRecord) record;
                    return ptr.getTarget().toString();
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}
 
源代码15 项目: mollyim-android   文件: CustomDns.java
private static @NonNull Lookup doLookup(@NonNull String hostname) throws UnknownHostException {
  try {
    return new Lookup(hostname);
  } catch (Throwable e) {
    Log.w(TAG, e);
    throw new UnknownHostException();
  }
}
 
/**
 * Follow the CNAME breadcrumb trail and find any which can't resolve
 * @param hostName a string of the hostname, or fqdn, to lookup 
 * @return a set of strings which list the CNAME entries which could not be resolved
 */
public Set<String> getBadCnames(String hostName){
    Set<String> retval = new TreeSet<String>();
    try {
        Lookup thisLookup = new Lookup(hostName, CNAME);
        thisLookup.setResolver(myResolver);
        Record[] results = thisLookup.run();
        if (results != null){
            List<Record> records = Arrays.asList(results);
            for (Record record : records){
                CNAMERecord thisRecord = (CNAMERecord) record;
                String target = thisRecord.getTarget().toString();
                if (hasRecordsOfType(target, CNAME)){
                    // check for more cnames down the tree
                    retval.addAll(getBadCnames(target));
                } else {
                    if (!(hasRecordsOfType(target, A) || hasRecordsOfType(target, AAAA))){
                        // This one doesn't point to anything
                        retval.add(target);
                    }
                }
            }
        }
    }
    catch (TextParseException e){
        System.err.println("[SRI][-] There was an error parsing the name " + hostName);
    }
    return retval;
}
 
源代码17 项目: ShadowsocksRR   文件: Utils.java
public static String resolve(String host, int addrType) {
    try {
        Lookup lookup = new Lookup(host, addrType);
        SimpleResolver resolver = new SimpleResolver("114.114.114.114");
        resolver.setTimeout(5);
        lookup.setResolver(resolver);
        Record[] result = lookup.run();
        if (result == null || result.length == 0) {
            return null;
        }

        List<Record> records = new ArrayList<>(Arrays.asList(result));
        Collections.shuffle(records);
        for (Record r : records) {
            switch (addrType) {
                case Type.A:
                    return ((ARecord) r).getAddress().getHostAddress();
                case Type.AAAA:
                    return ((AAAARecord) r).getAddress().getHostAddress();
                default:
                    break;
            }
        }
    } catch (Exception e) {
        VayLog.e(TAG, "resolve", e);
        app.track(e);
    }
    return null;
}
 
源代码18 项目: Maying   文件: Utils.java
public static String resolve(String host, int addrType) {
    try {
        Lookup lookup = new Lookup(host, addrType);
        SimpleResolver resolver = new SimpleResolver("114.114.114.114");
        resolver.setTimeout(5);
        lookup.setResolver(resolver);
        Record[] result = lookup.run();
        if (result == null || result.length == 0) {
            return null;
        }

        List<Record> records = new ArrayList<>(Arrays.asList(result));
        Collections.shuffle(records);
        for (Record r : records) {
            switch (addrType) {
                case Type.A:
                    return ((ARecord) r).getAddress().getHostAddress();
                case Type.AAAA:
                    return ((AAAARecord) r).getAddress().getHostAddress();
                default:
                    break;
            }
        }
    } catch (Exception e) {
        VayLog.e(TAG, "resolve", e);
        ShadowsocksApplication.app.track(e);
    }
    return null;
}
 
源代码19 项目: datawave   文件: RemoteHttpService.java
protected URIBuilder buildURI() throws TextParseException {
    final String host = serviceHost();
    final int port = servicePort();
    URIBuilder builder = new URIBuilder();
    builder.setScheme(serviceScheme());
    if (useSrvDns()) {
        List<LookupResult> results = dnsSrvResolver.resolve(host);
        if (results != null && !results.isEmpty()) {
            LookupResult result = results.get(0);
            builder.setHost(result.host());
            builder.setPort(result.port());
            // Consul sends the hostname back in its own namespace. Although the A record is included in the
            // "ADDITIONAL SECTION", Spotify SRV lookup doesn't translate, so we need to do the lookup manually.
            if (result.host().endsWith(".consul.")) {
                Record[] newResults = new Lookup(result.host(), Type.A, DClass.IN).run();
                if (newResults != null && newResults.length > 0) {
                    builder.setHost(newResults[0].rdataToString());
                } else {
                    throw new IllegalArgumentException("Unable to resolve service host " + host + " -> " + result.host() + " -> ???");
                }
            }
        } else {
            throw new IllegalArgumentException("Unable to resolve service host: " + host);
        }
    } else {
        builder.setHost(host);
        builder.setPort(port);
    }
    return builder;
}
 
源代码20 项目: Virtual-Hosts   文件: DNSJavaNameService.java
/**
 * Performs a reverse DNS lookup.
 * @param addr The ip address to lookup.
 * @return The host name found for the ip address.
 */
public String
getHostByAddr(byte [] addr) throws UnknownHostException {
	Name name = ReverseMap.fromAddress(InetAddress.getByAddress(addr));
	Record [] records = new Lookup(name, Type.PTR).run();
	if (records == null)
		throw new UnknownHostException();
	return ((PTRRecord) records[0]).getTarget().toString();
}
 
源代码21 项目: james-project   文件: DNSJavaService.java
/**
 * Looks up DNS records of the specified type for the specified name.
 * <p/>
 * This method is a public wrapper for the private implementation method
 *
 * @param namestr  the name of the host to be looked up
 * @param type     the type of record desired
 * @param typeDesc the description of the record type, for debugging purpose
 */
protected Record[] lookup(String namestr, int type, String typeDesc) throws TemporaryResolutionException {
    // Name name = null;
    try {
        // name = Name.fromString(namestr, Name.root);
        Lookup l = new Lookup(namestr, type);

        l.setCache(cache);
        l.setResolver(resolver);
        l.setCredibility(dnsCredibility);
        l.setSearchPath(searchPaths);
        Record[] r = l.run();

        try {
            if (l.getResult() == Lookup.TRY_AGAIN) {
                throw new TemporaryResolutionException("DNSService is temporary not reachable");
            } else {
                return r;
            }
        } catch (IllegalStateException ise) {
            // This is okay, because it mimics the original behaviour
            // TODO find out if it's a bug in DNSJava
            LOGGER.warn("Error determining result ", ise);
            throw new TemporaryResolutionException("DNSService is temporary not reachable");
        }

        // return rawDNSLookup(name, false, type, typeDesc);
    } catch (TextParseException tpe) {
        // TODO: Figure out how to handle this correctly.
        LOGGER.error("Couldn't parse name {}", namestr, tpe);
        return null;
    }
}
 
源代码22 项目: james-project   文件: DNSJavaServiceTest.java
@After
public void tearDown() throws Exception {
    dnsServer.setCache(null);
    dnsServer = null;
    Lookup.setDefaultCache(defaultCache, DClass.IN);
    Lookup.setDefaultResolver(defaultResolver);
    Lookup.setDefaultSearchPath(defaultSearchPaths);
}
 
源代码23 项目: dns-java   文件: SimpleLookupFactory.java
@Override
public Lookup forName(String fqdn) {
  try {
    final Lookup lookup = new Lookup(fqdn, Type.SRV, DClass.IN);
    if (resolver != null) {
      lookup.setResolver(resolver);
    }
    return lookup;
  } catch (TextParseException e) {
    throw new DnsException("unable to create lookup for name: " + fqdn, e);
  }
}
 
源代码24 项目: dns-java   文件: CachingLookupFactoryTest.java
@Before
public void setUp() throws Exception {
  delegate = mock(LookupFactory.class);

  factory = new CachingLookupFactory(delegate);

  lookup = new Lookup("hi");
  lookup2 = new Lookup("hey");
}
 
源代码25 项目: dns-java   文件: CachingLookupFactoryTest.java
@Test
public void shouldCacheResultsForSubsequentQueries() {
  when(delegate.forName("hej")).thenReturn(lookup, lookup2);

  Lookup first = factory.forName("hej");
  Lookup second = factory.forName("hej");

  assertThat(first == second, is(true));
}
 
源代码26 项目: dns-java   文件: CachingLookupFactoryTest.java
@Test
public void shouldReturnDifferentForDifferentQueries() {
  when(delegate.forName("hej")).thenReturn(lookup);
  when(delegate.forName("hopp")).thenReturn(lookup2);

  Lookup first = factory.forName("hej");
  Lookup second = factory.forName("hopp");

  assertThat(first == second, is(false));
}
 
源代码27 项目: dns-java   文件: CachingLookupFactoryTest.java
@Test
public void shouldReturnDifferentForDifferentThreads() throws Exception {
  ExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
  factory = new CachingLookupFactory(new SimpleLookupFactory());

  Lookup first = factory.forName("hej");
  Lookup second = executorService.submit(() -> factory.forName("hej")).get();

  assertThat(second, not(equalTo(first)));
}
 
源代码28 项目: dns-java   文件: SimpleLookupFactoryTest.java
@Test
public void shouldCreateNewLookupsEachTime() {
  Lookup first = factory.forName("some.other.name.");
  Lookup second = factory.forName("some.other.name.");

  assertThat(first == second, is(false));
}
 
源代码29 项目: AndroidPNClient   文件: DNSJavaNameService.java
/**
 * Performs a reverse DNS lookup.
 * @param addr The ip address to lookup.
 * @return The host name found for the ip address.
 */
public String
getHostByAddr(byte [] addr) throws UnknownHostException {
	Name name = ReverseMap.fromAddress(InetAddress.getByAddress(addr));
	Record [] records = new Lookup(name, Type.PTR).run();
	if (records == null)
		throw new UnknownHostException();
	return ((PTRRecord) records[0]).getTarget().toString();
}
 
源代码30 项目: mireka   文件: AddressLookup.java
private Record[] queryAddressRecords(Name name) throws SendException {
    Lookup lookup = new Lookup(name);
    Record[] records = lookup.run();
    switch (lookup.getResult()) {
    case Lookup.SUCCESSFUL:
        return records;
    case Lookup.TYPE_NOT_FOUND:
        throw new SendException("Host " + name + " has no address record ("
                + lookup.getErrorString() + ")",
                EnhancedStatus.PERMANENT_UNABLE_TO_ROUTE);
    case Lookup.HOST_NOT_FOUND:
        throw new SendException("Host " + name + " is not found ("
                + lookup.getErrorString() + ")",
                EnhancedStatus.PERMANENT_UNABLE_TO_ROUTE);
    case Lookup.TRY_AGAIN:
        throw new SendException(
                "DNS network failure while looking up address of " + name
                        + ": " + lookup.getErrorString(),
                EnhancedStatus.TRANSIENT_DIRECTORY_SERVER_FAILURE);
    case Lookup.UNRECOVERABLE:
        throw new SendException(
                "Unrecoverable DNS error while looking up address of "
                        + name + ": " + lookup.getErrorString(),
                EnhancedStatus.PERMANENT_UNABLE_TO_ROUTE);
    default:
        throw new SendException(
                "Unknown DNS status while looking up address of " + name
                        + ": " + lookup.getResult() + ". "
                        + lookup.getErrorString(),
                EnhancedStatus.PERMANENT_INTERNAL_ERROR);
    }
}