Skip to content

Instantly share code, notes, and snippets.

@dead-horse
Last active August 29, 2015 14:07
Show Gist options
  • Save dead-horse/9c6dd4f542e38622d351 to your computer and use it in GitHub Desktop.
Save dead-horse/9c6dd4f542e38622d351 to your computer and use it in GitHub Desktop.
var cp = require('child_process');
var urllib = require('urllib');
exports.ipMap = {};
var urls = [
'www.baidu.com',
'www.tmall.com'
];
urls.forEach(function (url) {
exports.ipMap[url] = {};
});
function traceAll() {
var hour = new Date().getHours();
urls.forEach(function (url) {
trace(url, function (err, ips) {
if (err) {
return console.error(err.stack);
}
var map = exports.ipMap[url];
map[hour].ips = ips;
});
})
}
setInterval(traceAll, 60 * 60 * 1000);
/**
* trace ips by traceroute
* return a list of ips
*/
function trace(url, callback) {
cp.exec('traceroute ' + url, {
timeout: 5 * 60 * 1000
}, function (err, stdout, stderr) {
if (err) {
return callback(err);
}
var out = stdout.split('\n');
var ips = [];
var count = 0;
out.forEach(function (o) {
var ip = getIp(o);
ip && ips.push(ip);
});
// get all locations by ips
getAllLocations(ips, function (err, ipWithLocations) {
callback(err, ipWithLocations);
});
});
}
/**
* get ip from string
*/
function getIp(str) {
var reg = /\d+\.\d+\.\d+\.\d+/;
var r = str.match(reg);
if (r) {
return r[0];
}
}
/**
* get all locations by ip list
*/
function getAllLocations(ips, callback) {
var ip = ips.unshift();
var res = [];
_get();
// get location one by one
function _get(ip) {
// if no left ip
// callback with the res
if (!ip) {
return callback(null, res);
}
// get location with ip
getLocation(ip, function (err, location) {
if (err) {
console.error(err.stack);
}
if (location) {
res.push({
ip: ip,
location: location
});
}
// try to get next one
_get(ips.unshift());
})
}
}
/**
* get location by ip
*/
function getLocation(ip, callback) {
urllib.request('http://xxx' + ip, function (err, data) {
//get the location
callback(err, location);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment