forked from 17mon/nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipx.js
72 lines (62 loc) · 2.25 KB
/
ipx.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var fs = require('fs');
var dns = require('dns');
var loadBinaryData = function(filepath){
var fd = fs.openSync(filepath, 'r');
var indexLengthBuffer = new Buffer(4);
var chunkSize = 102400,
chunkBuffer,
chunks = [];
var readLength = 0,
bufferLength = 0;
while (true) {
chunkBuffer = new Buffer(chunkSize);
readLength = fs.readSync(fd, chunkBuffer, 0, chunkSize, bufferLength);
bufferLength += readLength;
chunks.push(chunkBuffer);
if (readLength < chunkSize) break;
}
fs.closeSync(fd);
return Buffer.concat(chunks);
};
var IpFind = function(ip){
if (dataBuffer == null) {
return [];
}
var ipArray = ip.trim().split('.'),
ip2long = function(ip){return new Buffer(ip.trim().split('.')).readInt32BE(0)},
ipInt = ip2long(ip);
var offset = dataBuffer.readInt32BE(0);
var indexBuffer = dataBuffer.slice(4, offset - 4 + 4);
var tmp_offset = (parseInt(ipArray[0]) * 256 + parseInt(ipArray[1])) * 4;
var start = indexBuffer.slice(tmp_offset, tmp_offset + 4).readInt32LE(0);
var max_comp_len = offset - 262144 - 4;
var index_offset = -1, index_length = -1;
for (start = start * 9 + 262144; start < max_comp_len; start += 9) {
if (indexBuffer.slice(start, start + 4).readInt32BE(0) >= ipInt) {
index_offset = ((indexBuffer[start + 6] << 16) + (indexBuffer[start + 5] << 8) + indexBuffer[start + 4]);
index_length = (indexBuffer[start + 7] << 8) + indexBuffer[start + 8];
break;
}
}
if (index_offset == -1 || index_length == -1) {
return [];
} else {
return dataBuffer.slice(offset + index_offset - 262144, offset + index_offset - 262144 + index_length).toString('utf-8').split("\t");
}
};
var dataBuffer = null;
exports.load = function(file){
if (dataBuffer == null) {
dataBuffer = loadBinaryData(file);
}
}
exports.find = function(name, callback){
dns.resolve4(name, function (err, addresses) {
if (err) {
callback(IpFind(name));
} else {
callback(IpFind(addresses.shift()));
}
});
};
exports.findSync = IpFind;