Skip to content

Instantly share code, notes, and snippets.

@fouber
Created November 12, 2016 04:41
Show Gist options
  • Save fouber/40949d049130134a91c45d1084af558a to your computer and use it in GitHub Desktop.
Save fouber/40949d049130134a91c45d1084af558a to your computer and use it in GitHub Desktop.
shadowsocks-check
var spawn = require('child_process').spawn;
var chalk = require('chalk');
function format(data){
var lost, rtt;
data.replace(/([\d.]+%) packet loss| = ([\d.]+)\/([\d.]+)\/([\d.]+)\/([\d.]+) ms/g, function(m, $1, $2, $3, $4, $5){
if($1){
lost = $1;
} else if($3) {
rtt = $3
}
});
return {
lost: lost,
rtt: Number(rtt || -1)
};
}
function check(host, callback){
var count = 5;
var ping = spawn('ping', [ '-c', count, host ]);
var result = '';
var last = Date.now();
process.stdout.write('ping ' + host + ' ');
ping.stdout.on('data', function(data){
result += data.toString('utf8');
result = result.replace(/64 bytes from [\d.]+: icmp_seq=\d+ ttl=\d+ time=([\d.]+) ms[\n\r]+|Request timeout for icmp_seq (\d+)[\n\r]+/g, function(m, $1, $2){
count--;
if($2){
process.stdout.write(chalk.bold.red('■'));
} else {
$1 = Number($1);
// console.log('time: %d', $1);
if($1 > 200){
process.stdout.write(chalk.bold.black('■'));
} else if($1 > 100){
process.stdout.write(chalk.bold.grey('■'));
} else if($1 > 50){
process.stdout.write(chalk.bold.yellow('■'));
} else {
process.stdout.write(chalk.bold.green('■'));
}
}
return '';
});
});
ping.stderr.on('data', function(data){
console.log('stderr: ' + data);
});
ping.on('close', function(code){
if(count > 0){
var str = (new Array(count + 1)).join('■');
process.stdout.write(chalk.bold.red(str));
}
var opt = format(result);
process.stdout.write(' lost: ' + opt.lost + '\trtt: ' + opt.rtt + 'ms\n');
// console.log(result);
// console.log(opt);
opt.host = host;
callback(opt);
});
}
var list = [
'hk100.bsv1.net',
'hk102.bsv1.net',
'kr100.bsv1.net',
'jp100.bsv1.net',
'jp101.bsv1.net',
'sg100.bsv1.net',
'sg101.bsv1.net',
'tw100.bsv1.net',
'us100.bsv1.net',
'us101.bsv1.net',
];
var best = {
host: list[0],
lost: '100%',
rtt: Infinity
};
(function(b){
if(b.rtt > 0 && b.rtt < best.rtt){
best = b;
}
if(list.length){
check(list.shift(), arguments.callee);
} else {
console.log('---------------------------------------------------------');
console.log('Top 1: %s, lost: %s, rtt: %sms', best.host, best.lost, best.rtt);
}
})(best);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment