node自学之路(2) node实现DNS查询
/** * Created by iwang on 2017/2/16. */ var http = require('http'), //服务器创建 dns = require('dns'), //DNS查询 fs = require('fs'), //文件操作 url = require('url'), //url操作 querystring = require('querystring'); //字符串处理 http.createServer(function (req,res) { req.setEncoding('utf8'); res.writeHead(200,{'Content-Type':'text/html'}); // var readPath = __dirname+'/'+url.parse('index.html').pathname; var pathname = url.parse(req.url).pathname; // var indexPage = fs.readFileSync(readPath); router(res,req,pathname) }).listen(3000,'127.0.0.1'); console.log('server begin'); function router(res,req,pathname) { switch (pathname){ case "/parse": parseDns(res,req) break; default: goIndex(res,req) } } function goIndex(res,req) { console.log() var readPath = __dirname + '\\' + url.parse('index.html').pathname; var indexPage = fs.readFileSync('index.html'); console.log(indexPage) res.end(indexPage) } function parseDns(res,req) { var poseData = ""; req.addListener('data',function (poseDataChunk) { poseData += poseDataChunk; }); req.addListener('end',function () { var retData = getDns(poseData,function (domain,addresses) { res.writeHead(200,{'Content-Type':'text/html'}); res.end('<!DOCTYPE html>\ <html lang="en">\ <head>\ <meta charset="UTF-8">\ <title>DNS查询</title>\ <meta http-equiv="content-type" content="text/html;charset=utf-8">\ </head>\ <body>\ <div style="text-align: center;">\ Domain:<span style="color:red">'+domain+'</span>\ IP:<span style="color:red">'+addresses.join(',')+'</span>\ </div>\ </body>\ </html>') }); return; }) } function getDns(posedata,callback) { var domain = querystring.parse(posedata).search_dns; dns.resolve(domain,function (err, addresses) { if(!addresses){ addresses = ['不存在域名'] } callback(domain,addresses) }) }
输入www.baidu.com域名测试:
结果: