Node.JS解析DNS(NodeJS開發實戰詳解)

Node.JS解析DNS(NodeJS開發實戰詳解)

Node.JS解析DNS(NodeJS開發實戰詳解)

本篇博文實現使用Node.JS解析DNS:
需要載入的模組:

  • var http = require(‘http’) //伺服器建立
  • dns = require(‘dns’) //DNS查詢
  • fs =require(‘fs’) //檔案操作
  • url = require(‘url’)//url處理
  • querystring = require(“querystring”)//字串處理

下面是parse_dns.js檔案程式碼:

/* 首先 require 載入需要的 Node.js 原生模組 */
var http = require('http'), //伺服器建立
dns = require('dns'), //DNS查詢
fs = require('fs'),  //檔案操作
url = require('url') //url 處理
querystring = require("querystring") //字串處理
/* 建立http 伺服器*/
http.createServer(function (req, res) {
/* 寫 http head 返回html,因此Content-Type為html*/
var pathname = url.parse(req.url).pathname
req.setEncoding("utf8");
res.writeHead(200, {'Content-Type':'text/html'});
router(res,req,pathname);
}).listen(3000,'127.0.0.1');
/* 列印執行log*/
console.log('Server running at http:127.0.01');
function router(res, req, pathname) {
switch(pathname){
case "/parse":
parseDns(res,req);
break;
default:
goIndex(res,req);
}
}
function parseDns(res,req){
var postData = "";
req.addListener("data",function (postDataChunk) {
postData  = postDataChunk;
});
req.addListener("end",function () {
var retData = getDns(postData,function (domain,addresses) {
res.writeHead(200, {'Content-Type':'text/html'});
res.end("<html><head><meta http-equiv='content-type' "  
"content='text/html;charset=utf-8'></head><div style='text-align:center'>"  
"Domain:<span style='color:red'>"   domain   ""  
"</span> IP:<span style='color:red'>"  
addresses.join(',')   "</span></div></html>");
});
return;
});
}
function goIndex(res,req) {
var readPath = __dirname   '/'   url.parse('index.html').pathname;
var indexPage = fs.readFileSync(readPath);
/*返回*/
res.end(indexPage);
}
function getDns(postData,callback){
var domain = querystring.parse(postData).search_dns
dns.resolve(domain, function (err, address) {
if(!address){
address = ['不存在域名']
}
callback(domain,address);
});
}

下面是index.html檔案程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DNS查詢</title>
</head>
<body>
<h1 style="text-align: center">DNS 查詢工具</h1>
<div style="text-align: center">
<form action="/parse" method="post">
查詢DNS: <input type="text" name="search_dns">
<input type="submit" value="查詢">
</form>
<div id='check_result'></div>
</div>
</body>
</html>

執行parse_dns.js並在瀏覽器輸入127.0.0.1:3000之後會顯示如下介面:
這裡寫圖片描述

在輸入框中輸入網址,點選查詢之後的結果:
這裡寫圖片描述