NODEJS IP归属地查询类

 1 /**
 2 获取IP信息 归属地 ISP
 3 */
 4 IPInfo = function(ip, callback)
 5 {
 6     this.http = require('http');
 7 }
 8 
 9 IPInfo.prototype.log = function(str)
10 {
11     console.log(str);
12 }
13 
14 IPInfo.prototype.GetUrl = function(ip)
15 {
16     var url = '/iplookup/iplookup.php?format=json&ip=' + ip;
17     return url;
18 }
19 
20 IPInfo.prototype.GetHost = function()
21 {
22     var host = 'int.dpool.sina.com.cn';
23     return host;
24 }
25 
26 IPInfo.prototype.GetInfo = function(ip, callback)
27 {
28     var options = {
29         host:        this.GetHost(),
30         port:        null,
31         path:        this.GetUrl(ip)
32     }
33     
34     var curtThis = this;
35     var req = this.http.get(options, function(res){
36         res.setEncoding('utf8');
37         var data = "";
38         res.on('data', function (chunk) {
39             data += chunk;
40         });
41         
42         res.on("end", function() {
43             callback(data);
44             //curtThis.log(data);
45         });
46     });
47     
48     req.on('error', function(e) {
49         callback(null, e);
50         //curtThis.log("error");
51     });
52     
53     req.end();
54 }
55 
56 
57 //example
58 /*
59 var test = new IPInfo();
60 
61 var info = ["221.8.120.56","221.8.120.56","123.172.68.122"];
62 
63 for(var i=0;i<3;i++)
64 {
65 test.GetInfo(info[i], function(data, err){
66     if(err){console.log(err)}
67     else
68         console.log(data);
69 });
70 }
71 */

用的新浪的接口查询的IP

你可能感兴趣的:(nodejs)