Skip to content

Instantly share code, notes, and snippets.

@caok
Created February 8, 2014 07:22
Show Gist options
  • Save caok/8877936 to your computer and use it in GitHub Desktop.
Save caok/8877936 to your computer and use it in GitHub Desktop.
如何在Node.js中获取本机IP地址
//获取本地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);
}
})
});
@iahu
Copy link

iahu commented Mar 23, 2016

windows 下情况也不一样。得依据系统区分来写

@code4lala
Copy link

Windows 10 下是 key === '以太网'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment