Aug 09
家中或者公司使用了 Tomato 或者 DD-WRT 固件路由器的同学可能想分享他们的“私密” Hosts 文件,但是又不方便拷贝到每台机器,那么把这个 Hosts 文件内容放到路由器上是最方便的,不过 DNSMasq 的 Hosts 文件与 Windows 的 Hosts 文件格式不同,需要做一个转换,于是有了下面这个 HTML 文件,其实就是一个简单的 Javascript 转换。复制所有内容,存为任意命名的 HTML 文件,用浏览器打开,然后点击转换按钮,把转换后的数据贴到路由器 DNS 设置界面就行了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hosts2DNSMasq</title>
<script type="text/javascript">
//类似 PHP 中的 trim
function trim(str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
//转换 Hosts 文件格式到 DNSMasq 的格式
function htol(el) {
var i;
var localz = new Array();
var hosts = document.getElementById(el).value;
var localzs='';
hostdomain = hosts.split("\n");
for (i=0;i<hostdomain.length;i++) {
if (trim(hostdomain[i]) != '') {
localz[i] = hostdomain[i].split("\t");
if (localz[i][1] != undefined && localz[i][0].indexOf("#") == -1) {
localzs += 'address=/'+localz[i][1]+'/'+localz[i][0]+'\n';
} else {
localzs += hostdomain[i]+'\n';
}
}
}
document.getElementById(el).value = localzs;
}
</script>
</head>
<body>
<div style="width:1024px; margin:0 auto;">
<h2>HOSTS</h2>
<div style="margin: 5px auto; display: block;">
<button type="button" id="hosttolocal" onclick="htol('hostsMap');">ConventerToDNSMASQ</button>
</div>
<textarea id="hostsMap" onclick="this.focus();this.select()" style="width:98%;height:550px;margin:0;padding:3px;display:block;"></textarea>
</div>
</body>
</html>
例如以下的 Hosts 数据:
203.208.45.200 base0.googlehosted.com
203.208.45.200 base1.googlehosted.com
203.208.45.200 base2.googlehosted.com
203.208.45.200 base3.googlehosted.com
203.208.45.200 base4.googlehosted.com
203.208.45.200 base5.googlehosted.com
203.208.45.200 bks0.books.google.com
203.208.45.200 bks1.books.google.com
会被转换成:
address=/base0.googlehosted.com/203.208.45.200
address=/base1.googlehosted.com/203.208.45.200
address=/base2.googlehosted.com/203.208.45.200
address=/base3.googlehosted.com/203.208.45.200
address=/base4.googlehosted.com/203.208.45.200
address=/base5.googlehosted.com/203.208.45.200
address=/bks0.books.google.com/203.208.45.200
address=/bks1.books.google.com/203.208.45.200
注意,只是做了简单的格式转换,没有利用 DNSMasq 的(泛域名)特性优化。
引用本文,复制粘贴...