Permalink
Browse files

Initial version

  • Loading branch information...
0 parents commit 4516fe74bdb9d8d2ff1af3c1be891a7da757ea63 @carter-thaxton committed Aug 20, 2010
Showing with 126 additions and 0 deletions.
  1. +27 −0 README.md
  2. +99 −0 macaddr.js
27 README.md
@@ -0,0 +1,27 @@
+macaddr.js
+==========
+Gets the MAC addresses for the current machine.
+
+Comes in two forms, one to get the first address found, and one to get them all.
+
+ var macaddr = require('macaddr');
+
+<strong>macaddr.address()</strong>
+
+ macaddr.address(function(err, addr) {
+ if (addr) {
+ console.log('MAC address: ' + addr);
+ } else {
+ console.log('MAC address not found');
+ }
+ });
+
+<strong>macaddr.all_addresses()</strong>
+
+ macaddr.all_addresses(function(err, addrs) {
+ if (addrs && addrs.length > 0) {
+ console.log('MAC addresses: ' + JSON.stringify(addrs));
+ } else {
+ console.log('No MAC addresses found');
+ }
+ });
99 macaddr.js
@@ -0,0 +1,99 @@
+var exec = require('child_process').exec;
+
+var re = /[^:\-](?:[0-9A-F][0-9A-F][:\-]){5}[0-9A-F][0-9A-F][^:\-]/i;
+var cmds = ['/sbin/ifconfig', '/bin/ifconfig', 'ifconfig', 'ipconfig /all'];
+
+var results = null;
+var cbs = [];
+
+var find_addresses = function(cb) {
+ var i = 0;
+
+ function run_cmd() {
+ var cmd = cmds[i];
+ exec(cmd, function(err, stdout, stderr) {
+ var lines, line, match, cb, j;
+ if (!err) {
+ lines = stdout.split('\n');
+ for (j = 0; j < lines.length; j++) {
+ line = lines[j];
+ match = re.exec(line);
+ if (match) {
+ match = match.toString().trim();
+ if (match.length) {
+ if (!results) {
+ results = [];
+ }
+ results.push(match);
+ }
+ }
+ }
+ }
+
+ if (results && results.length > 0) {
+ done();
+ } else {
+ i += 1;
+ if (i < cmds.length) {
+ run_next_cmd();
+ } else {
+ done();
+ }
+ }
+ });
+ };
+
+ // Avoid calling out to the shell multiple times.
+ // Queue up any callbacks, and call them all when done.
+ var done = function() {
+ while (cbs.length) {
+ cb = cbs.shift();
+ cb();
+ }
+ };
+
+ if (results === null) {
+ cbs.push(cb);
+ if (cbs.length === 1) {
+ run_cmd();
+ }
+ } else {
+ cb();
+ }
+};
+
+var address = function(cb) {
+ if (!(cb instanceof Function)) {
+ throw new Error('Argument to address must be a callback function');
+ }
+
+ var respond = function() {
+ if (results && results.length >= 1) {
+ cb(undefined, results[0]);
+ } else {
+ cb('No MAC addresses found');
+ }
+ }
+
+ find_addresses(respond);
+};
+
+
+var all_addresses = function(cb) {
+ if (!(cb instanceof Function)) {
+ throw new Error('Argument to all_addresses must be a callback function');
+ }
+
+ var respond = function() {
+ if (results !== null) {
+ cb(undefined, results);
+ } else {
+ cb('No MAC addresses found');
+ }
+ }
+
+ find_addresses(respond);
+};
+
+exports.address = address;
+exports.all_addresses = all_addresses;

0 comments on commit 4516fe7

Please sign in to comment.