如何在Node.js中获取本机本地IP地址

来源:互联网 发布:ubuntu怎么增加分辨率 编辑:程序博客网 时间:2024/04/29 01:43

最近在做Cloud related的项目时,遇到一个问题,就是如何在Node.js中获取本机的IP地址。Node.js提供的API中,只能获取本机的hostname.

os = require('os');console.log(os.hostname());

但要希望得到本机IP的话,node.js就无能为力了。

 

先在Google上search了一下,发现一个关于这个问题比较好的讨论,Get local IP address in node.js。其中提到通过exec('ipconfig')+正则表达式来处理。

但是,新的问题出现了。node.js 中的exec是异步执行,我不知道什么时候exec执行完,当然也就不知道什么时候去取ip地址了。在万般无奈的情况下,只能

监听node.js中process对象的close事件,确保exec("ipconfig")执行完后,再做其他处理。

 

代码如下:

os = require('os');child_proc = require('child_process');var getIPApp = undefined;var matches = [];var pmHosts = [];var filterRE = undefined; var pingResult = null;var pmHost = null;if ('win32' == os.platform()) {getIPApp = child_proc.spawn("ipconfig", null);// only get the IPv4 addressfilterRE = /\b(IPv4|IP\s)[^:\r\r\n]+:\s+([^\s]+)/g;}else {// TODO: we need try to get the local IP for other os, such as unix/mac return false;}getIPApp.on('exit', function (code, signal) {matches = pingResult.match(filterRE) || [];for (var i = 0; i < matches.length; i++) {var host = matches[i].split(':')[1];// trim the spaces in the string's start/end position.host = host.replace(/(^[\s]*)|([\s]*$)/g,"");pmHosts.push(host);}if (pmHosts.length > 0)pmHost = pmHosts[0];// do other thingsconsole.log(pmHost);});getIPApp.stdout.on('data', function (data) {// get ping result.pingResult = pingResult + data.toString();});


 上述方法仅支持windows平台,只是用来获取IPV4格式的IP地址。在Win7 64, WinXp 32测试通过。

如果需要在其它平台下运行,请修改ipconfig.如希望获取IPV6格式的IP地址,请修改正则表达式。


Update

目前,在node.js(v0.8.16)上,可以使用以下代码来获取本IP地址

var os=require('os');var ifaces=os.networkInterfaces();for (var dev in ifaces) {  var alias=0;  ifaces[dev].forEach(function(details){    if (details.family=='IPv4') {      console.log(dev+(alias?':'+alias:''),details.address);      ++alias;    }  });}