org.xbill.DNS.SimpleResolver Java Examples

The following examples show how to use org.xbill.DNS.SimpleResolver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleResolverCheck.java    From entrada with GNU General Public License v3.0 7 votes vote down vote up
@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();
}
 
Example #2
Source File: DNS.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Constructor
 * 
 * @param timeoutInSeconds the timeout for queries in seconds, 0 means infinite
 * @param nLog             optional Log instance for logging
 */
public DNS (int timeoutInSeconds, Log nLog) {
	log = nLog;
	if (timeoutInSeconds > 0) {
		try {
			resolv = new SimpleResolver ();
			resolv.setTimeout (timeoutInSeconds);
		} catch (UnknownHostException e) {
			if (log != null) {
				log.out (Log.WARNING, "dns", "Failed to find proper DNS host: " + e.toString ());
			}
			resolv = null;
		}
	} else {
		resolv = null;
	}
}
 
Example #3
Source File: CustomDns.java    From KinoCast with MIT License 6 votes vote down vote up
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");
    }
}
 
Example #4
Source File: AndroidResolverConfigProvider.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void initializeApi26Nameservers() throws InitializationException {
  if (context == null) {
    throw new InitializationException("Context must be initialized by calling setContext");
  }

  ConnectivityManager cm = context.getSystemService(ConnectivityManager.class);
  Network network = cm.getActiveNetwork();
  if (network == null) {
    // if the device is offline, there's no active network
    return;
  }

  LinkProperties lp = cm.getLinkProperties(network);
  if (lp == null) {
    // can be null for an unknown network, which may happen if networks change
    return;
  }

  for (InetAddress address : lp.getDnsServers()) {
    addNameserver(new InetSocketAddress(address, SimpleResolver.DEFAULT_PORT));
  }

  parseSearchPathList(lp.getDomains(), ",");
}
 
Example #5
Source File: Helperfunctions.java    From open-rmbt with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: Utils.java    From ShadowsocksRR with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #7
Source File: Utils.java    From Maying with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #8
Source File: GcpIpRanges.java    From quarantyne with Apache License 2.0 5 votes vote down vote up
public GcpIpRanges() {
  try {
    this.resolver = new SimpleResolver("8.8.8.8");
  } catch (UnknownHostException uex) {
    log.error("cannot instantiate resolver", uex);
  }
}
 
Example #9
Source File: OpenAliasHelper.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Override
protected Boolean doInBackground(String... args) {
    //main();
    if (args.length != 1) return false;
    String name = args[0];
    if ((name == null) || (name.isEmpty()))
        return false; //pointless trying to lookup nothing
    Timber.d("Resolving %s", name);
    try {
        SimpleResolver sr = new SimpleResolver(DNSSEC_SERVERS[new Random().nextInt(DNSSEC_SERVERS.length)]);
        ValidatingResolver vr = new ValidatingResolver(sr);
        vr.setTimeout(0, DNS_LOOKUP_TIMEOUT);
        vr.loadTrustAnchors(new ByteArrayInputStream(ROOT.getBytes("ASCII")));
        Record qr = Record.newRecord(Name.fromConstantString(name + "."), Type.TXT, DClass.IN);
        Message response = vr.send(Message.newQuery(qr));
        final int rcode = response.getRcode();
        if (rcode != Rcode.NOERROR) {
            Timber.i("Rcode: %s", Rcode.string(rcode));
            for (RRset set : response.getSectionRRsets(Section.ADDITIONAL)) {
                if (set.getName().equals(Name.root) && set.getType() == Type.TXT
                        && set.getDClass() == ValidatingResolver.VALIDATION_REASON_QCLASS) {
                    Timber.i("Reason:  %s", ((TXTRecord) set.first()).getStrings().get(0));
                }
            }
            return false;
        } else {
            dnssec = response.getHeader().getFlag(Flags.AD);
            for (Record record : response.getSectionArray(Section.ANSWER)) {
                if (record.getType() == Type.TXT) {
                    txts.addAll(((TXTRecord) record).getStrings());
                }
            }
        }
    } catch (IOException | IllegalArgumentException ex) {
        return false;
    }
    return true;
}
 
Example #10
Source File: DnsSrvResolversIT.java    From dns-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnResultsUsingSpecifiedServers() throws Exception {
  final String server = new SimpleResolver().getAddress().getHostName();
  final DnsSrvResolver resolver = DnsSrvResolvers
      .newBuilder()
      .servers(List.of(server))
      .build();
  assertThat(resolver.resolve("_spotify-client._tcp.spotify.com").isEmpty(), is(false));
}
 
Example #11
Source File: PropertyResolverConfigProvider.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Initializes the servers, search path and ndots setting with from the property names passed as
 * the arguments.
 *
 * @param serverName the property name for the DNS servers
 * @param searchName the property name for the search path
 * @param ndotsName the property name for the ndots setting
 * @since 3.2
 */
protected void initialize(String serverName, String searchName, String ndotsName) {
  String servers = System.getProperty(serverName);
  if (servers != null) {
    StringTokenizer st = new StringTokenizer(servers, ",");
    while (st.hasMoreTokens()) {
      String server = st.nextToken();
      try {
        URI uri = new URI("dns://" + server);
        // assume this is an IPv6 address without brackets
        if (uri.getHost() == null) {
          addNameserver(new InetSocketAddress(server, SimpleResolver.DEFAULT_PORT));
        } else {
          int port = uri.getPort();
          if (port == -1) {
            port = SimpleResolver.DEFAULT_PORT;
          }

          addNameserver(new InetSocketAddress(uri.getHost(), port));
        }
      } catch (URISyntaxException e) {
        log.warn("Ignored invalid server {}", server);
      }
    }
  }

  String searchPathProperty = System.getProperty(searchName);
  parseSearchPathList(searchPathProperty, ",");

  String ndotsProperty = System.getProperty(ndotsName);
  ndots = parseNdots(ndotsProperty);
}
 
Example #12
Source File: AndroidResolverConfigProvider.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void initializeNameservers() {
  for (int i = 1; i <= 4; i++) {
    String server = SystemProperties.get("net.dns" + i);
    if (server != null && !server.isEmpty()) {
      addNameserver(new InetSocketAddress(server, SimpleResolver.DEFAULT_PORT));
    }
  }
}
 
Example #13
Source File: Helperfunctions.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
public static Long getASN(final InetAddress adr)
{
    try
    {
        final Name postfix;
        if (adr instanceof Inet6Address)
            postfix = Name.fromConstantString("origin6.asn.cymru.com");
        else
            postfix = Name.fromConstantString("origin.asn.cymru.com");
        
        final Name name = getReverseIPName(adr, postfix);
        System.out.println("lookup: " + name);
        
        final Lookup lookup = new Lookup(name, Type.TXT);
        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 TXTRecord)
                {
                    final TXTRecord txt = (TXTRecord) record;
                    @SuppressWarnings("unchecked")
                    final List<String> strings = txt.getStrings();
                    if (strings != null && !strings.isEmpty())
                    {
                        final String result = strings.get(0);
                        final String[] parts = result.split(" ?\\| ?");
                        if (parts != null && parts.length >= 1)
                            return new Long(parts[0]);
                    }
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}
 
Example #14
Source File: Helperfunctions.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
public static String getASName(final long asn)
{
    try
    {
        final Name postfix = Name.fromConstantString("asn.cymru.com.");
        final Name name = new Name(String.format("AS%d", asn), postfix);
        System.out.println("lookup: " + name);
        
        final Lookup lookup = new Lookup(name, Type.TXT);
        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 TXTRecord)
                {
                    final TXTRecord txt = (TXTRecord) record;
                    @SuppressWarnings("unchecked")
                    final List<String> strings = txt.getStrings();
                    if (strings != null && !strings.isEmpty())
                    {
                        System.out.println(strings);
                        
                        final String result = strings.get(0);
                        final String[] parts = result.split(" ?\\| ?");
                        if (parts != null && parts.length >= 1)
                            return parts[4];
                    }
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}
 
Example #15
Source File: Helperfunctions.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
public static String getAScountry(final long asn)
{
    try
    {
        final Name postfix = Name.fromConstantString("asn.cymru.com.");
        final Name name = new Name(String.format("AS%d", asn), postfix);
        System.out.println("lookup: " + name);
        
        final Lookup lookup = new Lookup(name, Type.TXT);
        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 TXTRecord)
                {
                    final TXTRecord txt = (TXTRecord) record;
                    @SuppressWarnings("unchecked")
                    final List<String> strings = txt.getStrings();
                    if (strings != null && !strings.isEmpty())
                    {
                        final String result = strings.get(0);
                        final String[] parts = result.split(" ?\\| ?");
                        if (parts != null && parts.length >= 1)
                            return parts[1];
                    }
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}