写登录接口的时候,突然想如果登录的时候保存当前登录的IP会怎样,然后我就开始了,嘿嘿
1、当前获取请求的IP
//获取当前用户的IP
let getClientIp = function (req) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress || '';
};
let ip = getClientIp(req).match(/\d+.\d+.\d+.\d+/);
console.log(ip);
ip = ip ? ip.join('.') : null;
console.log(ip);
2、获取当前本机IP地址
const os = require('os');
//获取本机ip
let getIPAdress = function() {
var interfaces = 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;
}
}
}
}
let ip = getIPAdress();
console.log(ip);//196.128.239.1
感觉还不错!