5Mi / wumi_blog

for recording improvimg my experience
21 stars 0 forks source link

nodejs中ip有关地址的获取 #75

Open 5Mi opened 7 years ago

5Mi commented 7 years ago
//node获取url请求客户端ip
const getClientIp = (req) => {
  let ip = req.headers['x-forwarded-for'] ||
      req.ip ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.connection.socket.remoteAddress || '';
  if(ip.split(',').length>0){
      ip = ip.split(',')[0]
  }
  return ip;
};
const checkIsInsideIP = (req) => {
  //node檢查是否是內部 IP(内网ip)
  //1.A類地址中:10.0.0.0到10.255.255.255.255
  //2.B類地址中:172.16.0.0到172.31.255.255
  //3.C類地址中:192.168.0.0到192.168.255.255

  var ip = req.connection.remoteAddress;
  var address = ip.split(':');
  var ipAddress = address[3];

  if (ipAddress == "127.0.0.1" || ipAddress == "localhost")
  {
    return true;
  }

  var aryIpAddress = ipAddress.split('.');

  if (aryIpAddress[0] == "10") {
    return true;
  }

  if (aryIpAddress[0] == "192" && aryIpAddress[1] == "168") {
    return true;
  }

  if (aryIpAddress[0] == "172") {
    var num = parseInt(aryIpAddress[1]);
    if (num >= 16 && num <= 31) {
      return true;
    }
  }

  return false;
}
//node获取服务器内网ip
var os=require('os'),
    iptable={},
    ifaces=os.networkInterfaces();
for (var dev in ifaces) {
  ifaces[dev].forEach(function(details,alias){
    if (details.family=='IPv4') {
      iptable[dev+(alias?':'+alias:'')]=details.address;
    }
  });
}
console.log(iptable);