Created
          November 18, 2011 16:43 
        
      - 
      
 - 
        
Save dakatsuka/1376992 to your computer and use it in GitHub Desktop.  
    Node.jsでIPアドレスを取得
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | var ifconfig = require('./ifconfig'); | |
| ifconfig.inet4(function(result) { | |
| console.log(result); | |
| }); | 
  
    
      This file contains hidden or 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
    
  
  
    
  | 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