java 如何动态修改DNS,对host动态绑定即时生效

 

 

1.windows下

  1.1 在java中直接设置:

           java.security.Security.setProperty("networkaddress.cache.ttl" , "0");

        java.security.Security.setProperty("networkaddress.cache.negative.ttl" , "0");

 

      然后修改host文件的绑定直接就能生效。

 

    1.2 通过反射修改jdk的DNS缓存,在windows下修改host之后也能直接生效。

        

 

 


                 
public static void jdkDnsNoCache() throws SecurityException, NoSuchFieldException, IllegalArgumentException,                  IllegalAccessException{
Class clazz = java.net.InetAddress.class;
                final Field cacheField = clazz.getDeclaredField("addressCache");
                cacheField.setAccessible(true);
                final Object o = cacheField.get(clazz);
                Class clazz2 = o.getClass();
                 final Field cacheMapField = clazz2.getDeclaredField("cache");
                cacheMapField.setAccessible(true);
                final Map cacheMap = (Map)cacheMapField.get(o);
                AccessController.doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        try{
                            synchronized(o){//同步是必须的,因为o可能会有多个线程同时访问修改。
//                                cacheMap.clear();//这步比较关键,用于清除原来的缓存
                                    cacheMap.remove("www.baidu.com");
                            }   
                        }catch(Throwable te){
                            throw new RuntimeException(te);
                        }   
                        return null;
                    }   
                }); 
                
        }     

    2.linux下:

      2.1除了在java中设置      

        java.security.Security.setProperty("networkaddress.cache.ttl" , "0");

        java.security.Security.setProperty("networkaddress.cache.negative.ttl" , "0");

      还需要启动一个脚本:执行这个脚本才能修改host文件后直接生效。 脚本执行间隔根据需求定。

        #!/bin/sh

  while [ true ]
  do
  /etc/init.d/nscd restart
  done

    这个脚本也可以使用java 的runtime来执行。

    public static String getTestUrlHtml(String url, String host, String ip) throws IOException{

                java.security.Security.setProperty("networkaddress.cache.ttl" , "0");
                java.security.Security.setProperty("networkaddress.cache.negative.ttl" , "0");
                Process processTest = Runtime.getRuntime().exec("/etc/init.d/nscd restart");
                addHostBinding(ip,host);
                String res = getResponseText(url);
                Process process = Runtime.getRuntime().exec("/etc/init.d/nscd restart");
                //Process process2 = Runtime.getRuntime().exec("/etc/init.d/nscd restart");
                deleteHostBinding(ip, host);
                System.err.println(getResponseText("http://www.baidu.com"));
                Process process3 = Runtime.getRuntime().exec("/etc/init.d/nscd restart");
                process.destroy();
                processTest.destroy();
                process3.destroy();
                return res;
        }  

 

 

2.2 同样上面windows下通过反射修改jdk的DNS缓存,同样再执行下面这个脚本就ok了。

 

附上测试程序:

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


public class HostUtil3 {

	public static final String  hostFilePath="C:\\Windows\\System32\\drivers\\etc\\hosts";
//	public static final String  hostFilePath="/etc/hosts";
	
	public static void addHostBinding(String ip, String host){
		Map<String,String>  hostToIpMap = readFromIpHostFile();
		hostToIpMap.put(host, ip);
		writeIpHostToReader(hostToIpMap);
	}
	
	public static void deleteHostBinding(String ip, String host){
		Map<String,String>  hostToIpMap = readFromIpHostFile();
		if(hostToIpMap != null && hostToIpMap.containsKey(host)){
			hostToIpMap.remove(host);
		}
		writeIpHostToReader(hostToIpMap);
	}
	
	public static Map<String,String> readFromIpHostFile(){
		Map<String,String>  hostToIpMap = new HashMap<String,String>();
		BufferedReader bufferReader= null;
		try {
			bufferReader = new BufferedReader(new FileReader(hostFilePath));
			String str = null;
			while((str = bufferReader.readLine()) != null){
				if(str != null){
					String[] ipAndHost = str.split(" ");
					if(ipAndHost != null && ipAndHost.length == 2 && ipAndHost[0] != null && ipAndHost[0].charAt(0) != '#'){
						hostToIpMap.put(ipAndHost[1], ipAndHost[0]);
					}
				}
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try{
				bufferReader.close();
			}catch(Exception e){
				
			}
		}
		return hostToIpMap;
	}
	
	public static void writeIpHostToReader(Map<String,String> hostToIpMap){
		BufferedWriter bufferedWriter = null;
		try {
			bufferedWriter = new BufferedWriter(new FileWriter(hostFilePath));
			Iterator<Entry<String,String>> iter = hostToIpMap.entrySet().iterator();
			while(iter.hasNext()){
				Entry<String,String> entry = iter.next();
				bufferedWriter.write(entry.getValue() + "   " + entry.getKey() + "\n");
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try{
				bufferedWriter.close();
			}catch(Exception e){
				
			}
		}
	}
	
	/**
	 * 请求接口数据并返回每一行的数据列表
	 * 
	 * @param queryUrl
	 * @return
	 */
	public static String getResponseText(String queryUrl) {
		InputStream is = null;
		BufferedReader br = null;
		StringBuffer res = new StringBuffer();
		try {
			URL url = new URL(queryUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url
					.openConnection();
			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setConnectTimeout(2000);

			is = httpUrlConn.getInputStream();

			br = new BufferedReader(new InputStreamReader(is, "utf-8"));

			String data = null;
			while ((data = br.readLine()) != null) {
				res.append(data + "\n");
			}
			return res.toString();

		} catch (IOException e) {
		} catch (Exception e) {
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
		return null;
	}
	
	public static void jdkDnsNoCache() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
		 Class clazz = java.net.InetAddress.class;
	        final Field cacheField = clazz.getDeclaredField("addressCache");
	        cacheField.setAccessible(true);
	        final Object o = cacheField.get(clazz);
	        Class clazz2 = o.getClass();
	         final Field cacheMapField = clazz2.getDeclaredField("cache");
	        cacheMapField.setAccessible(true);
	        final Map cacheMap = (Map)cacheMapField.get(o);
	        AccessController.doPrivileged(new PrivilegedAction() {
	            public Object run() {
	                try{
	                    synchronized(o){//同步是必须的,因为o可能会有多个线程同时访问修改。
//	                        cacheMap.clear();//这步比较关键,用于清除原来的缓存
	                    	cacheMap.remove("www.baidu.com");
	                    }   
	                }catch(Throwable te){
	                    throw new RuntimeException(te);
	                }   
	                return null;
	            }   
	        }); 
	        
	}
	
	
	public static void test() throws IOException, InterruptedException{
		addHostBinding("127.0.0.1","www.baidu.com");
		System.err.println(getResponseText("http://www.baidu.com"));

		System.err.println("************************************************************");
		deleteHostBinding("127.0.0.1","www.baidu.com");
		try {
			jdkDnsNoCache();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        InetAddress address = InetAddress.getByName("www.baidu.com");
        System.out.println(System.currentTimeMillis()+":::"+address.getHostAddress());
		System.err.println(getResponseText("http://www.baidu.com"));
	}
	
	public static void main(String[] args) throws IOException, InterruptedException{
		test();
//		updateDNS();
	}
	
}
 

 

在windows下得输出:

 

 null
************************************************************
1319035631098:::119.75.217.56
<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>?????????????      </title><style>html{overflow-y:auto}body{font:12px arial;text-align:center;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}#u{padding:7px 10px 3px 0;text-align:right}#m{width:680px;margin:0 auto}#nv{font-size:16px;margin:0 0 4px;text-align:left;text-indent:117px}#nv a,#nv b,.btn,#lk{font-size:14px}#fm{padding-left:90px;text-align:left}#kw{width:404px;height:22px;padding:4px 7px;padding:6px 7px 2px\9;font:16px arial;background:url(http://www.baidu.com/img/i-1.0.0.png) no-repeat -304px 0;_background-attachment:fixed;border:1px solid #cdcdcd;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.btn{width:95px;height:32px;padding:0;padding-top:2px\9;border:0;background:#ddd url(http://www.baidu.com/img/i-1.0.0.png) no-repeat;cursor:pointer}.btn_h{background-position:-100px 0}#kw,.btn_wr{margin:0 5px 0 0}.btn_wr{width:97px;height:34px;display:inline-block;background:url(http://www.baidu.com/img/i-1.0.0.png) no-repeat -202px 0;_top:1px;*position:relative}#lk{margin:33px 0}#lk span{font:14px "????"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}.tools{position:absolute;top:-4px;*top:10px;right:-13px;}#mHolder{width:62px;position:relative;z-index:296;display:none}#mCon{height:18px;line-height:18px;position:absolute;cursor:pointer;padding:0 18px 0 0;background:url(http://www.baidu.com/img/bg-1.0.0.gif) no-repeat right -134px;background-position:right -136px\9}#mCon span{color:#00c;cursor:default;display:block}#mCon .hw{text-decoration:underline;cursor:pointer}#mMenu{width:56px;border:1px solid #9a99ff;list-style:none;position:absolute;right:7px;top:28px;display:none;background:#fff}#mMenu a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none}#mMenu a:hover{background:#d9e1f6}#mMenu .ln{height:1px;background:#ccf;overflow:hidden;margin:2px;font-size:1px;line-height:1px}#cp,#cp a{color:#77c}#sh{display:none;behavior:url(#default#homepage)}</style>
</head>
<body><div id="u"><a href="http://www.baidu.com/gaoji/preferences.html" name="tj_setting">????????</a>&nbsp;|&nbsp;<a href="http://passport.baidu.com/?login&tpl=mn" name="tj_login">???</a></div>
<div id="m"><p id="lg"><img src="http://www.baidu.com/img/baidu_sylogo1.gif" width="270" height="129" usemap="#mp"><map name="mp"><area shape="rect" coords="40,25,230,95" href="http://hi.baidu.com/baidu/" target="_blank" title="?????? ??????" ></map></p><p id="nv"><a href="http://news.baidu.com">??&nbsp;??</a>??<b>??&nbsp;?</b>??<a href="http://tieba.baidu.com">??&nbsp;??</a>??<a href="http://zhidao.baidu.com">?&nbsp;??</a>??<a href="http://mp3.baidu.com">MP3</a>??<a href="http://image.baidu.com">?&nbsp;?</a>??<a href="http://video.baidu.com">??&nbsp;?</a>??<a href="http://map.baidu.com">??&nbsp;?</a></p><div id="fm"><form name="f" action="/s"><input type="text" name="wd" id="kw" maxlength="100"><input type="hidden" name="rsv_bp" value="0"><input type="hidden" name="rsv_spt" value="3"><span class="btn_wr"><input type="submit" value="??????" id="su" class="btn" οnmοusedοwn="this.className='btn btn_h'" οnmοuseοut="this.className='btn'"></span></form><span class="tools"><span id="mHolder"><div id="mCon"><span>????</span></div></span></span><ul id="mMenu"><li><a href="#" name="ime_hw">??д</a></li><li><a href="#" name="ime_py">???</a></li><li class="ln"></li><li><a href="#" name="ime_cl">???</a></li></ul></div>
<p id="lk"><a href="http://hi.baidu.com">???</a>??<a href="http://baike.baidu.com">???</a>??<a href="http://www.hao123.com">hao123</a><span> | <a href="/more/">???&gt;&gt;</a></span></p><p id="lm"></p><p><a id="sh" onClick="this.setHomePage('http://www.baidu.com')" href="http://utility.baidu.com/traf/click.php?id=215&url=http://www.baidu.com" οnmοusedοwn="return ns_c({'fm':'behs','tab':'homepage','pos':0})">??????????</a></p>
<p id="lh"><a href="http://e.baidu.com/?refer=888">?????????</a> | <a href="http://top.baidu.com">?????????</a> | <a href="http://home.baidu.com">??????</a> | <a href="http://ir.baidu.com">About Baidu</a></p><p id="cp">&copy;2011 Baidu <a href="/duty/">?????????</a> <a href="http://www.miibeian.gov.cn" target="_blank">??ICP?030173??</a> <img src="http://gimg.baidu.com/img/gs.gif"></p></div></body>
<script>var w=window,d=document,n=navigator,k=d.f.wd,a=d.getElementById("nv").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.opera,sh=d.getElementById("sh");if(isIE&&sh&&!sh.isHomePage("http://www.baidu.com")){sh.style.display="inline"}for(var i=0;i<a.length;i++){a[i].οnclick=function(){if(k.value.length>0){var C=this,A=C.href,B=encodeURIComponent(k.value);if(A.indexOf("q=")!=-1){C.href=A.replace(/q=[^&\x24]*/,"q="+B)}else{this.href+="?q="+B}}}}(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(RegExp["\x241"])}})();if(n.cookieEnabled&&!/sug?=0/.test(d.cookie)){d.write("<script src=http://www.baidu.com/js/bdsug.js?v=1.0.3.0><\/script>")}function addEV(C,B,A){if(w.attachEvent){C.attachEvent("on"+B,A)}else{if(w.addEventListener){C.addEventListener(B,A,false)}}}function G(A){return d.getElementById(A)}function ns_c(E){var F=encodeURIComponent(window.document.location.href),D="",A="",B="",C=window["BD_PS_C"+(new Date()).getTime()]=new Image();for(v in E){A=E[v];D+=v+"="+A+"&"}B="&mu="+F;C.src="http://nsclick.baidu.com/v.gif?pid=201&pj=www&"+D+"path="+F+"&t="+new Date().getTime();return true}if(/\bbdime=[12]/.test(d.cookie)){document.write("<script src=http://www.baidu.com/cache/ime/js/openime-1.0.0.js><\/script>")}(function(){var B=G("user"),A=G("userMenu");if(B&&A){addEV(B,"click",function(C){A.style.display=A.style.display=="block"?"none":"block";window.event?C.cancelBubble=true:C.stopPropagation()});addEV(document,"click",function(){A.style.display="none"})}})();(function(){var E=G("u").getElementsByTagName("a"),C=G("nv").getElementsByTagName("a"),I=G("lk").getElementsByTagName("a"),B="";var A=["news","tieba","zhidao","mp3","img","video","map"];var H=["hi","baike","hao123","more"];if(G("un")&&G("un").innerHTML!=""){B=G("un").innerHTML}function D(J){addEV(J,"mousedown",function(L){var L=L||window.event;var K=L.target||L.srcElement;ns_c({fm:"behs",tab:K.name||"tj_user",un:encodeURIComponent(B)})})}for(var F=0;F<E.length;F++){D(E[F])}for(var F=0;F<C.length;F++){C[F].name="tj_"+A[F];D(C[F])}for(var F=0;F<I.length;F++){I[F].name="tj_"+H[F];D(I[F])}})();addEV(w,"load",function(){k.focus()});w.οnunlοad=function(){};</script>


<script type="text/javascript" src="http://www.baidu.com/cache/hps/js/hps-1.1.1.js"></script>
</html><!--6f1d70970a531a5f-->
 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值