下面列出了怎么用org.xbill.DNS.Lookup的API类实例代码及写法,或者点击链接到github查看源代码。
@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();
}
@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);
}
@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()));
}
}
@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);
}
@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());
}
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");
}
}
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);
}
}
}
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);
}
}
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;
}
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;
}
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;
}
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 "";
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
/**
* 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();
}
/**
* 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;
}
}
@After
public void tearDown() throws Exception {
dnsServer.setCache(null);
dnsServer = null;
Lookup.setDefaultCache(defaultCache, DClass.IN);
Lookup.setDefaultResolver(defaultResolver);
Lookup.setDefaultSearchPath(defaultSearchPaths);
}
@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);
}
}
@Before
public void setUp() throws Exception {
delegate = mock(LookupFactory.class);
factory = new CachingLookupFactory(delegate);
lookup = new Lookup("hi");
lookup2 = new Lookup("hey");
}
@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));
}
@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));
}
@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)));
}
@Test
public void shouldCreateNewLookupsEachTime() {
Lookup first = factory.forName("some.other.name.");
Lookup second = factory.forName("some.other.name.");
assertThat(first == second, is(false));
}
/**
* 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();
}
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);
}
}