nodejs client forward

This commit is contained in:
dongyado 2016-07-06 11:27:58 +08:00
parent 0dd1a53d00
commit 401e5bc795
2 changed files with 30 additions and 13 deletions

View File

@ -11,40 +11,53 @@ function Ip2region(db_path)
{
var fs = require('fs');
var ipbase = [16777216, 65536, 256, 1]; // for ip2long
var ip2r = {};
ip2r.db_file_path = null;
ip2r.db_fd = null;
var db_file_path = null;
var db_fd = null;
// db file check
if (typeof(db_path) == "undefined" || fs.exists(db_path) ) {
throw("[ip2region] db file not exists : " + db_path);
}
ip2r.db_file_path = db_path;
db_file_path = db_path;
try {
ip2r.db_fd = fs.openSync(ip2r.db_file_path, 'r');
db_fd = fs.openSync(db_file_path, 'r');
} catch(e) {
throw("[ip2region] Can not open ip2region.db file , path : " + ip2r.db_file_path);
throw("[ip2region] Can not open ip2region.db file , path : " + db_file_path);
}
var totalBlocks = 0;
var firstIndexPtr = 0;
var lastIndexPtr = 0;
var superBlock = new Buffer(8);
this.binarySearch = function(ip)
{
var buffer = new Buffer(8);
fs.readSync(ip2r.db_fd, buffer, 0, 8, 0);
if (typeof(ip) == 'string') ip = ip2long(ip);
console.log(getLong(buffer, 0));
console.log(getLong(buffer, 4));
// init basic search environment
if (totalBlocks == 0) {
fs.readSync(ip2r.db_fd, superBlock, 0, 8, 0);
firstIndexPtr = getLong(superBlock, 0);
lastIndexPtr = getLong(superBlock, 4);
}
// search
return ip2long(ip);
}
this.btreeSearch = function(ip)
{
return ip2long(ip);
}
/**
* convert ip to long (xxx.xxx.xxx.xxx to a integer)
* */
function ip2long(ip)
{
var val = 0;
@ -55,11 +68,15 @@ function Ip2region(db_path)
return val;
}
/**
* get long value from buffer with specified offset
* */
function getLong(buffer, offset)
{
return (
(buffer[offset] & 0x000000FF ) |
((buffer[offset + 1] << 8) & 0x0000FF00) |
(buffer[offset] & 0x000000FF) |
((buffer[offset + 1] << 8) & 0x0000FF00) |
((buffer[offset + 2] << 16) & 0x00FF0000) |
((buffer[offset + 3] << 24) & 0xFF000000)
);

View File

@ -5,4 +5,4 @@
var Ip2region = require('./ip2region');
var ip2region = new Ip2region('../../data/ip2region.db');
console.log(ip2region.binarySearch("114.114.114.114"));
console.log(ip2region.binarySearch("255.255.255.255"));