Skip to content

Instantly share code, notes, and snippets.

@hyysguyang
Created August 10, 2016 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyysguyang/33063df4d9c73d51328a1e835ab7fe7c to your computer and use it in GitHub Desktop.
Save hyysguyang/33063df4d9c73d51328a1e835ab7fe7c to your computer and use it in GitHub Desktop.
DNSJava demo
package com.lansent.demo;
import org.junit.Assert;
import org.junit.Test;
import org.xbill.DNS.*;
import java.io.IOException;
import java.net.InetAddress;
/**
* @author <a href="mailto:hyysguyang@gmail.com">Young Gu</a>
* @author <a href="mailto:guyang@lansent.com">Young Gu</a>
* @Date 8/10/16 10:06 PM
*/
public class DnsTest {
@Test
public void testCustomizedDNS() throws IOException {
String ipFromSystemDNS = resolveHostWithSystemDNS();
ARecord ipFromCustomizedDNS = resolveHostWithCustomizedDNS("bing.com", "8.8.8.8");
Assert.assertEquals(ipFromSystemDNS,ipFromCustomizedDNS.getAddress().getHostAddress());
}
private String resolveHostWithSystemDNS() {
try {
return InetAddress.getByName("bing.com").getHostAddress();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private ARecord resolveHostWithCustomizedDNS(String host, String dnsServer) throws IOException {
final Name full = Name.concatenate(Name.fromString(host), Name.root);
final Resolver res = new SimpleResolver(dnsServer);
res.setTimeout(500);
final Record question = Record.newRecord(full, Type.A, DClass.IN);
final Message response = res.send(Message.newQuery(question));
final RRset[] answer = response.getSectionRRsets(Section.ANSWER);
return (ARecord)answer[0].rrs().next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment