Java動態解析域名html
Java提供InetAddress類,能夠對域名-IP進行正向、逆向解析。java
InetAddress解析的時候通常是調用系統自帶的DNS程序。linux
linux 默認的DNS方式是讀取/etc/resolv.conf進行DNS解析。apache
mac 默認的方式是向網關請求獲取DNS服務器,而後直接請求DNS服務器進行解析,沒有讀取/etc/resolv.conf。服務器
個人業務是根據不一樣的DNS分別解析域名,所以須要動態的設置DNS。oracle
These properties may not be supported in future releases.dom
Prior to JDK 7, the first provider that was successfully loaded was used. In JDK 7, providers are chained, which means that if a lookup on a provider fails, the next provider in the list is consulted to resolve the name.ide
import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.log4j.Logger; public class ResolveDomain { private Logger log = Logger.getLogger(ResolveDomain.class); public static void main(String[] args) throws UnknownHostException { ResolveDomain rd = new ResolveDomain(); rd.resolveDomain("www.baidu.com", "114.114.114.114", new ConcurrentLinkedQueue<String>()); }
public void resolveDomain(String domain, String DNS, ConcurrentLinkedQueue<String> queue){ System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun"); System.setProperty("sun.net.spi.nameservice.nameservers", DNS); InetAddress[] addresses; try { addresses = InetAddress.getAllByName(domain); //IP or domain for (int i = 0; i < addresses.length; i++) { String ip = addresses[i].getHostAddress(); log.info(DNS + "\t" + domain + "\t" + ip); queue.add(DNS + "\t" + domain + "\t" + ip); } } catch (UnknownHostException e) { e.printStackTrace(); } } }
ps:對於有些域名,例如www.baidu.com,在不一樣地區擁有不一樣的IP;所以使用不一樣的DNS服務器進行解析,獲得的IP通常也不同。 ui
參考博客: http://blog.chinaunix.net/uid-192452-id-3981087.htmlthis
http://www.jianshu.com/p/f10808ae4b60
https://docs.oracle.com/javase/8/docs/technotes/guides/net/properties.html
https://docs.oracle.com/javase/8/docs/technotes/guides/net/properties.html
https://www.cnblogs.com/549294286/p/5307316.html
http://blog.csdn.net/mofenglian/article/details/74344631