Skip to content

获取本地ip与公网ip

  • 以下两种实现方案均为网络收集,验证有效

获取本机本地ip

js
function getIPAddress(){
    var interfaces = require('os').networkInterfaces();
    for(var devName in interfaces){
        var iface = interfaces[devName];
        for(var i=0;i<iface.length;i++){
            var alias = iface[i];
            if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
                return alias.address;
            }
        }
    }
  }
console.log(getIPAddress()) // 本地ip

使用第三方模块:request-ip封装中间件获取用户公网ip

js
const requestIp = require('request-ip');
// inside middleware handler
const ipMiddleware = function(req, res, next) {
    const clientIp = requestIp.getClientIp(req); 
    next()
}
// on localhost you'll see 127.0.0.1 if you're using IPv4 
// or ::1, ::ffff:127.0.0.1 if you're using IPv6
// 封装成全局可使用的中间件
const requestIp = require('request-ip');
app.use(requestIp.mw())
app.use(function(req, res) {
    const ip = req.clientIp;
    res.end(ip);
})

使用第三方模块:public-ip获取本机公网ip

详见:https://github.com/sindresorhus/public-ip

js
npm install --save public-ip // 先安装依赖
// 在需要的地方require
const publicIp = require('public-ip') // 获取外网ip
publicIp.v4().then((ip) => console.log(ip)) // 调用模块提供的api即可获取

使用第三方模块:internal-ip获取本机内网ip

详见:https://github.com/sindresorhus/internal-ip

js
const internalIp = require('internal-ip'); // 在需要的地方require
(async () => {
	console.log(await internalIp.v6());
    //=> 'fe80::1'

    console.log(await internalIp.v4());
    //=> '10.0.0.79'
})()
console.log(internalIp.v6.sync()) //  'fe80::1'
console.log(internalIp.v4.sync()) //  '10.0.0.79'
npm install --save public-ip // 先安装依赖