Node.js – IP Lookup HttpServer

Meine erste Node.js – Anwendung ist nun fertig. Nach ein paar kniffen und viel kämpfen mit den Scopes habe ich eine Anwendung fertig gestellt, welche die IP einer Website sucht und findet.

Die Eingabe im Browser erfolgt so: http://localhost:3000/domain

Beispiele:
http://localhost:3000/https://gist.github.com/1360795

http://localhost:3000/google.de

http://localhost:3000/writedown.eu
http://localhost:3000/de-de.facebook.com
http://localhost:3000/www.inf.h-brs.de

Ausgabe:

Die IP von 'nodejs.org' ist 8.12.44.238

Weiter IP Adressen:

localhost: 127.0.0.1
google.de: 209.85.148.106
writedown.eu: 80.67.17.127
de-de.facebook.com: 66.220.158.53
www.inf.h-brs.de: 194.95.64.18

 

Dazu muss einfach nur der Node.js – Server laufen mit folgendem Code:

var http = require("http");
var dns = require("dns");
var u = require("util");

var urls = { length: 0 }

http.createServer(function(req,res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    var url = req.url.replace(/^\/(https?:\/\/)?/i,"");
    url = url.split("/")[0];

    var writeIp = function(wurl, wip) {
        res.write(String(wurl) + ": " + String(wip) + "\n");
    };

    var finished = function() {
        if(urls[url] == "undefined") {
            res.write("Die IP von '" + url + "' konnte nicht gefunden werden.\n");
        } else {
            res.write("Die IP von '" + url + "' ist " + String(urls[url]) + "\n");
        }
        if(url != "favicon.ico")
            console.log("Die IP von '" + url + "' wurde nachgeschaut. Die IP ist " + urls[url]);
        if(urls.length > 1 || ( urls.length > 0 && urls[url] == "undefined" )  ) {
            res.write("\n\n\nWeiter IP Adressen:\n\n");
        };

        for( var key in urls ) {
            if( key != "undefined" && key != url && key != "length" && urls[key] != "undefined") {
                writeIp(key, urls[key]);
            };
        };
        res.end("");
    };

    var cb = function(err, adress, family) {
        if(url != "favicon.ico") {
            if( urls[url] == undefined && String(adress) != "undefined") {
                urls.length += 1;
            };
            urls[url] = String(adress);
        };
        finished();
    };

    dns.lookup(url, cb);

}).listen(3000);

About Adrian

Wohnort: Siegburg Tätigkeit: Student (Wirtschaftsinformatik)
This entry was posted in IT, Node JS and tagged , , , , , , , , . Bookmark the permalink.

Kommentare sind deaktiviert.