Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
5Mi opened this issue Aug 24, 2017 · 0 comments
Open

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

5Mi opened this issue Aug 24, 2017 · 0 comments

Comments

@5Mi
Copy link
Owner

5Mi commented Aug 24, 2017

//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;
};
  • node判断是否为内网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
//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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant