Skip to content

Instantly share code, notes, and snippets.

@dakatsuka
Created November 18, 2011 16:43
Show Gist options
  • Save dakatsuka/1376992 to your computer and use it in GitHub Desktop.
Save dakatsuka/1376992 to your computer and use it in GitHub Desktop.
Node.jsでIPアドレスを取得
var ifconfig = require('./ifconfig');
ifconfig.inet4(function(result) {
console.log(result);
});
var exec = require('child_process').exec;
var Ifconfig = function() {
this.regexp = {};
switch (process.platform) {
case 'darwin':
this.command = 'ifconfig';
this.regexp.inet4 = /\binet\s+([^\s]+)/g;
this.regexp.inet6 = /\binet6\s+([^\s]+)/g;
break;
default:
this.command = 'ifconfig';
this.regexp.inet4 = /\binet\b[^:]+:\s*([^\s]+)/g;
this.regexp.inet6 = /\binet6\b[^:]+:\s*([^\s]+)/g;
break;
}
};
Ifconfig.prototype.inet4 = function(callback) {
var self = this;
exec(self.command, function(error, stdout, sterr) {
var ips = [];
var matches = stdout.match(self.regexp.inet4);
for (var i = 0; i < matches.length; i++) {
ips.push(matches[i].replace(self.regexp.inet4, "$1"));
if (i == matches.length -1) {
callback(ips);
}
}
});
};
Ifconfig.prototype.inet6 = function(callback) {
var self = this;
exec(self.command, function(error, stdout, sterr) {
var ips = [];
var matches = stdout.match(self.regexp.inet6)
for (var i = 0; i < matches.length; i++) {
ips.push(matches[i].replace(self.regexp.inet6, "$1"));
if (i == matches.length -1) {
callback(ips);
}
}
});
};
module.exports = new Ifconfig;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment