zoukankan      html  css  js  c++  java
  • 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域名测试:

    结果:

  • 相关阅读:
    sprintboot 发布
    springmvc 常用注解
    react-navigation使用技巧
    Windows 10提示你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问
    Python 精选文章
    自动化办公:python操作Excel
    VSCode 插件
    使用 Visual Studio Code(VSCode)搭建简单的Python+Django开发环境的方法步骤
    纯洁的微笑
    初进python世界之数据类型
  • 原文地址:https://www.cnblogs.com/iwang5566/p/6407863.html
Copyright © 2011-2022 走看看