Last active
December 11, 2015 22:39
-
-
Save jrgm/4671512 to your computer and use it in GitHub Desktop.
Count the tcp socket states from `ss(8)`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Count the tcp socket states from `ss(8)` | |
// usage: `while [ 1 ]; do ss -tanp | node ~/parse-ss-localports.js; sleep 5; done` | |
var _ = require('underscore'); | |
var FIELDS = { STATE: 0, RECVQ: 1, SENDQ: 2, LOCAL: 3, REMOTE: 4 }; | |
function uniqueEphemeral(list) { | |
return _.uniq(list).filter(isEphemeral).length; | |
} | |
function isEphemeral(val) { | |
// adjust as needed: on linux `cat /proc/sys/net/ipv4/ip_local_port_range` | |
return val >= 32768 && val <= 61000; | |
} | |
function consumeData(str) { | |
var stats = { | |
states: {}, | |
localports: [], | |
remoteports: [] | |
}; | |
str.split('\n').forEach(function(line) { | |
if (line.indexOf('State') === 0 || !line) return; // header or blank | |
var fields = line.split(/\s+/); | |
var state = fields[FIELDS.STATE]; | |
if (stats.states[state] === undefined) { | |
stats.states[state] = 0; | |
} | |
stats.states[state] += 1; | |
var local = fields[FIELDS.LOCAL].match(/:(\d+)$/); | |
if (local) { | |
stats.localports.push(parseInt(local[1], 10)); | |
} | |
var remote = fields[FIELDS.REMOTE].match(/:(\d+)$/); | |
if (remote) { | |
stats.remoteports.push(parseInt(remote[1], 10)); | |
} | |
}); | |
stats.localports = uniqueEphemeral(stats.localports); | |
stats.remoteports = uniqueEphemeral(stats.remoteports); | |
console.log(new Date().toISOString(), JSON.stringify(stats)); | |
} | |
process.stdin.resume(); | |
process.stdin.setEncoding('utf8'); | |
var data = ''; | |
process.stdin.on('data', function (chunk) { | |
data += chunk; | |
}); | |
process.stdin.on('end', function () { | |
consumeData(data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment