org.xbill.DNS.Record Java Examples

The following examples show how to use org.xbill.DNS.Record. 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: XBillDnsSrvResolver.java    From dns-java with Apache License 2.0 7 votes vote down vote up
@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()));
  }
}
 
Example #2
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 #3
Source File: IpAddressUtil.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
private static String reverseDnsLookupUsingDnsJavaSimpleResolver(long ipAddress) throws IOException {
    String result = null;
    byte[] address = convertLongAddressToBuf(ipAddress);
    Name name = ReverseMap.fromAddress(InetAddress.getByAddress(address));
    Record record = Record.newRecord(name, Type.PTR, DClass.IN);
    Message query = Message.newQuery(record);
    Message response = simpleResolver.send(query);
    Record[] answers = response.getSectionArray(Section.ANSWER);
    if (answers.length != 0) {
        // If PTR-record exists this will be at index 1 or above (more than one PTR-record may exist)
        Record answer = (answers.length > 1) ? answers[1] : answers[0];  
        result = answer.rdataToString();
        // remove trailing "."
        result = result.endsWith(".") ? result.substring(0, result.length() - 1) : result;
    } else {
        throw new IOException("Empty DNS response.");
    }
    return result;
}
 
Example #4
Source File: GoogleResolverCheck.java    From entrada with GNU General Public License v3.0 6 votes vote down vote up
private List<String> parse(Record record) {
  TXTRecord txt = (TXTRecord) record;
  List<String> subnets = new ArrayList<>();

  @SuppressWarnings("unchecked")
  List<String> lines = txt.getStrings();
  for (String line : lines) {
    String[] parts = StringUtils.split(line, " ");
    if (parts.length == 2) {
      if (log.isDebugEnabled()) {
        log.debug("Add Google resolver IP range: " + parts[0]);
      }
      subnets.add(parts[0]);
    }
  }

  if (subnets.isEmpty()) {
    log.error("No Google resolver addresses found");
  }

  return subnets;
}
 
Example #5
Source File: DNSLookupService.java    From openvisualtraceroute with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Dns lookup more efficient than the INetAddress.getHostName(ip)
 *
 * @param hostIp
 * @return
 * @throws IOException
 */
public String dnsLookup(final String hostIp) {
	try {
		final Name name = ReverseMap.fromAddress(hostIp);
		final int type = Type.PTR;
		final int dclass = DClass.IN;
		final Record rec = Record.newRecord(name, type, dclass);
		final Message query = Message.newQuery(rec);

		final Message response = _resolver.send(query);

		final Record[] answers = response.getSectionArray(Section.ANSWER);
		if (answers.length > 0) {
			String ret = answers[0].rdataToString();
			if (ret.endsWith(".")) {
				ret = ret.substring(0, ret.length() - 1);
			}
			return ret;
		}
	} catch (final IOException e) {
		LOGGER.warn("Failed to resolve hostname for " + hostIp, e);
	}
	return UNKNOWN_HOST;
}
 
Example #6
Source File: SimpleDoTResolver.java    From androdns with Apache License 2.0 6 votes vote down vote up
private Message
sendAXFR(Message query) throws IOException {
    Name qname = query.getQuestion().getName();
    ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(qname, address, tsig);
    xfrin.setTimeout((int)(getTimeout() / 1000));
    xfrin.setLocalAddress(localAddress);
    try {
        xfrin.run();
    }
    catch (ZoneTransferException e) {
        throw new WireParseException(e.getMessage());
    }
    List records = xfrin.getAXFR();
    Message response = new Message(query.getHeader().getID());
    response.getHeader().setFlag(Flags.AA);
    response.getHeader().setFlag(Flags.QR);
    response.addRecord(query.getQuestion(), Section.QUESTION);
    Iterator it = records.iterator();
    while (it.hasNext())
        response.addRecord((Record)it.next(), Section.ANSWER);
    return response;
}
 
Example #7
Source File: DNS.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Query a text record for the given domain from DNS
 * 
 * @param domain the domain to lookup the DNS for a text record
 * @return       the text record content, if found, null otherwise
 */
@SuppressWarnings ("unchecked")
public String queryText (String domain) {
	String		rc = null;
	Record[]	r = query (domain, Type.TXT);
	
	if (r != null) {
		rc = "";
		for (int n = 0; n < r.length; ++n) {
			List <String>	answ = ((TXTRecord) r[n]).getStrings ();
			
			for (int m = 0; m < answ.size (); ++m) {
				String	s = answ.get (m);
				
				if ((s != null) && (s.length () > 0)) {
					rc += s;
				}
			}
		}
	}
	return rc;
}
 
Example #8
Source File: DNSJavaService.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public InetAddress getByName(String host) throws UnknownHostException {
    TimeMetric timeMetric = metricFactory.timer("getByName");
    String name = allowIPLiteral(host);

    try {
        // Check if its local
        if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) {
            return getLocalHost();
        }

        return org.xbill.DNS.Address.getByAddress(name);
    } catch (UnknownHostException e) {
        Record[] records = lookupNoException(name, Type.A, "A");

        if (records != null && records.length >= 1) {
            ARecord a = (ARecord) records[0];
            return InetAddress.getByAddress(name, a.getAddress().getAddress());
        } else {
            throw e;
        }
    } finally {
        timeMetric.stopAndPublish();
    }
}
 
Example #9
Source File: DNSJavaService.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<String> findTXTRecords(String hostname) {
    TimeMetric timeMetric = metricFactory.timer("findTXTRecords");
    List<String> txtR = new ArrayList<>();
    Record[] records = lookupNoException(hostname, Type.TXT, "TXT");

    try {
        if (records != null) {
            for (Record record : records) {
                TXTRecord txt = (TXTRecord) record;
                txtR.add(txt.rdataToString());
            }

        }
        return txtR;
    } finally {
        timeMetric.stopAndPublish();
    }
}
 
Example #10
Source File: DNSJavaService.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public String getHostName(InetAddress addr) {
    TimeMetric timeMetric = metricFactory.timer("getHostName");
    String result;
    Name name = ReverseMap.fromAddress(addr);
    Record[] records = lookupNoException(name.toString(), Type.PTR, "PTR");

    try {
        if (records == null) {
            result = addr.getHostAddress();
        } else {
            PTRRecord ptr = (PTRRecord) records[0];
            result = ptr.getTarget().toString();
        }
        return result;
    } finally {
        timeMetric.stopAndPublish();
    }
}
 
Example #11
Source File: XBillDnsSrvResolver.java    From dns-java with Apache License 2.0 6 votes vote down vote up
private static List<LookupResult> toLookupResults(Record[] queryResult) {
  ImmutableList.Builder<LookupResult> builder = ImmutableList.builder();

  if (queryResult != null) {
    for (Record record: queryResult) {
      if (record instanceof SRVRecord) {
        SRVRecord srvRecord = (SRVRecord) record;
        builder.add(LookupResult.create(srvRecord.getTarget().toString(),
                                        srvRecord.getPort(),
                                        srvRecord.getPriority(),
                                        srvRecord.getWeight(),
                                        srvRecord.getTTL()));
      }
    }
  }

  return builder.build();
}
 
Example #12
Source File: XBillDnsSrvResolverTest.java    From dns-java with Apache License 2.0 6 votes vote down vote up
private Message messageWithNodes(String query, String[] names) throws TextParseException {
  Name queryName = Name.fromString(query);
  Record question = Record.newRecord(queryName, Type.SRV, DClass.IN);
  Message queryMessage = Message.newQuery(question);
  Message result = new Message();
  result.setHeader(queryMessage.getHeader());
  result.addRecord(question, Section.QUESTION);

  for (String name1 : names) {
    result.addRecord(
        new SRVRecord(queryName, DClass.IN, 1, 1, 1, 8080, Name.fromString(name1)),
        Section.ANSWER);
  }

  return result;
}
 
Example #13
Source File: Dnsbl.java    From mireka with Apache License 2.0 6 votes vote down vote up
private String concatenateTxtRecordValues(Record[] records) {
    if (records == null || records.length == 0)
        return null;
    StringBuilder builder = new StringBuilder();
    for (Record record : records) {
        TXTRecord txtRecord = (TXTRecord) record;
        if (builder.length() != 0)
            builder.append(EOL);
        for (Object string : txtRecord.getStrings()) {
            if (builder.length() != 0)
                builder.append(EOL);
            builder.append(string);
        }
    }
    return builder.toString();
}
 
Example #14
Source File: AddressLookupTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryAddresses() throws SendException {
    new Expectations() {
        {
            lookup.run();
            result =
                    new Record[] {
                            new ARecord(HOST1_EXAMPLE_COM_NAME, 0, 0, IP1),
                            new ARecord(HOST1_EXAMPLE_COM_NAME, 0, 0, IP2)

                    };

        }
    };

    InetAddress[] addresses =
            addressLookup.queryAddresses(HOST1_EXAMPLE_COM_NAME);

    InetAddress[] expected = new InetAddress[] { IP1, IP2 };
    assertArrayEquals(expected, addresses);
}
 
Example #15
Source File: AddressLookupTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryAddressesIpv6() throws SendException {
    new Expectations() {
        {
            lookup.run();
            result =
                    new Record[] { new AAAARecord(HOST6_EXAMPLE_COM_NAME,
                            0, 0, IPV6)

                    };

        }
    };

    InetAddress[] addresses =
            addressLookup.queryAddresses(HOST1_EXAMPLE_COM_NAME);

    InetAddress[] expected = new InetAddress[] { IPV6 };
    assertArrayEquals(expected, addresses);
}
 
Example #16
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
Record parseRR(Tokenizer st, int classValue, long TTLValue) throws IOException {
  Name name = st.getName(zone);
  long ttl;
  int type;

  String s = st.getString();

  try {
    ttl = TTL.parseTTL(s);
    s = st.getString();
  } catch (NumberFormatException e) {
    ttl = TTLValue;
  }

  if (DClass.value(s) >= 0) {
    classValue = DClass.value(s);
    s = st.getString();
  }

  if ((type = Type.value(s)) < 0) {
    throw new IOException("Invalid type: " + s);
  }

  return Record.fromString(name, type, classValue, ttl, st, zone);
}
 
Example #17
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
void doProhibit(Tokenizer st) throws IOException {
  Tokenizer.Token token;
  Name name;
  Record record;
  int type;

  name = st.getName(zone);
  token = st.get();
  if (token.isString()) {
    if ((type = Type.value(token.value)) < 0) {
      throw new IOException("Invalid type: " + token.value);
    }
  } else {
    type = Type.ANY;
  }
  record = Record.newRecord(name, type, DClass.NONE, 0);
  query.addRecord(record, Section.PREREQ);
  print(record);
}
 
Example #18
Source File: dig.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
static void doAXFR(Message response) {
  System.out.println("; java dig 0.0 <> " + name + " axfr");
  if (response.isSigned()) {
    System.out.print(";; TSIG ");
    if (response.isVerified()) {
      System.out.println("ok");
    } else {
      System.out.println("failed");
    }
  }

  if (response.getRcode() != Rcode.NOERROR) {
    System.out.println(response);
    return;
  }

  for (Record record : response.getSection(Section.ANSWER)) {
    System.out.println(record);
  }

  System.out.print(";; done (");
  System.out.print(response.getHeader().getCount(Section.ANSWER));
  System.out.print(" records, ");
  System.out.print(response.getHeader().getCount(Section.ADDITIONAL));
  System.out.println(" additional)");
}
 
Example #19
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public <T extends Record> RRset findExactMatch(Name name, int type, int dclass, boolean glue) {
  Zone zone = findBestZone(name);
  if (zone != null) {
    return zone.findExactMatch(name, type);
  } else {
    List<RRset> rrsets;
    Cache cache = getCache(dclass);
    if (glue) {
      rrsets = cache.findAnyRecords(name, type);
    } else {
      rrsets = cache.findRecords(name, type);
    }
    if (rrsets == null) {
      return null;
    } else {
      return rrsets.get(0); /* not quite right */
    }
  }
}
 
Example #20
Source File: ForwardLookupHelper.java    From yeti with MIT License 6 votes vote down vote up
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;
}
 
Example #21
Source File: ForwardLookupHelper.java    From yeti with MIT License 6 votes vote down vote up
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;
}
 
Example #22
Source File: DNS.java    From yeti with MIT License 6 votes vote down vote up
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;
}
 
Example #23
Source File: NetworkTools.java    From yeti with MIT License 6 votes vote down vote up
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 "";
}
 
Example #24
Source File: DataAPI.java    From yeti with MIT License 6 votes vote down vote up
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;
}
 
Example #25
Source File: Dig.java    From open-rmbt with Apache License 2.0 6 votes vote down vote up
static void	doAXFR(Message response) throws IOException {
	System.out.println("; java dig 0.0 <> " + name + " axfr");
	if (response.isSigned()) {
		System.out.print(";; TSIG ");
		if (response.isVerified())
			System.out.println("ok");
		else
			System.out.println("failed");
	}

	if (response.getRcode() != Rcode.NOERROR) {
		System.out.println(response);
		return;
	}

	Record [] records = response.getSectionArray(Section.ANSWER);
	for (int i = 0; i < records.length; i++)
		System.out.println(records[i]);

	System.out.print(";; done (");
	System.out.print(response.getHeader().getCount(Section.ANSWER));
	System.out.print(" records, ");
	System.out.print(response.getHeader().getCount(Section.ADDITIONAL));
	System.out.println(" additional)");
}
 
Example #26
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 #27
Source File: DnsIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testDnsProducer() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("dns:lookup");
        }
    });

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        Record[] record = producer.requestBodyAndHeader("direct:start", null, DnsConstants.DNS_NAME, "redhat.com", Record[].class);

        Assert.assertEquals("redhat.com.", record[0].getName().toString());
        Assert.assertEquals(Type.A, record[0].getType());
    } catch (CamelExecutionException ex) {
        Throwable cause = ex.getCause();
        Assert.assertEquals("network error", cause.getMessage());
    } finally {
        camelctx.close();
    }
}
 
Example #28
Source File: lookup.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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);
    }
  }
}
 
Example #29
Source File: TldController.java    From yeti with MIT License 5 votes vote down vote up
public void expandDomain(String domainToCheck) throws TextParseException {
    String domainName = null;

    // Check for domain name alias - CNAME
    Record[] recs = new Lookup(domainToCheck, Type.CNAME).run();
    if (recs != null && recs.length != 0) {
        domainName = ((CNAMERecord) recs[0]).getName().canonicalize().toString(true);
        Log.debug("Found: " + domainName + "CNAME rec: " + domainName);
    }

    // Now get the SOA record that would signify a domain exists
    recs = new Lookup(domainToCheck, Type.SOA).run();
    for (int idx = 0; idx < retryCount; idx++) {
        if (recs != null) {
            if (domainName == null) {
                domainName = ((SOARecord) recs[0]).getName().canonicalize().toString(true);
                Log.debug("Found: " + domainName + " SOA rec: " + domainName);
            }

            DomainResult newDomain = new DomainResult(domainName);
            newDomain.setNameServer(((SOARecord) recs[0]).getHost().toString(true));
            newDomain.setAdminName(((SOARecord) recs[0]).getAdmin().toString(true));
            String name = domainToCheck.split("\\.", 2)[0];
            String tld = domainToCheck.split("\\.", 2)[1];
            newDomain.setRegistrant(NetworkTools.getHostNameWhoisResult(name, tld, true));
            Map<String, String> attrs = new HashMap<>();
            attrs.put(DataStore.DNS_RECORD, DataStore.SOA);
            newDomain.setAttributes(attrs);
            addResult(newDomain);
            break;
        }
    }
}
 
Example #30
Source File: DNSJavaNameService.java    From Virtual-Hosts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}