Created
February 8, 2014 07:22
-
-
Save caok/8877936 to your computer and use it in GitHub Desktop.
如何在Node.js中获取本机IP地址
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
//获取本地IP地址 | |
var os = require('os'); | |
var IPv4,hostName; | |
hostName=os.hostname(); | |
for(var i=0;i<os.networkInterfaces().eth0.length;i++){ | |
if(os.networkInterfaces().eth0[i].family=='IPv4'){ | |
IPv4=os.networkInterfaces().eth0[i].address; | |
} | |
} | |
console.log('----------local IP: '+IPv4); | |
console.log('----------local host: '+hostName); | |
//获取外网IP地址 | |
//需要添加库:npm install jquery | |
// npm install iconv-lite | |
var $ = require('jquery'), | |
iconv = require('iconv-lite'), | |
http = require('http'); | |
var options = { | |
host:'ip.qq.com', | |
port:80, | |
path:'/' | |
}; | |
var html = "";//http获取html字符串 | |
http.get(options, function (res) { | |
res.setEncoding('binary');//or hex | |
res.on('data',function (data) {//加载数据,一般会执行多次 | |
html += data; | |
}).on('end', function () { | |
html=iconv.decode(new Buffer(html,'binary'), 'GBK');//把gbk编码转换成 | |
var dom = $(html); | |
var ip=dom.find("#login_show .red").text(); | |
if(ip.split('.').length==4){ | |
console.log('server ip: '+ip); | |
} | |
}) | |
}); |
windows 下情况也不一样。得依据系统区分来写
Windows 10 下是 key === '以太网'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
获取本地ip会报错。networkInterfaces()是对象不是数组。修改代码如下: