function_extend.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * Created by benzhan on 15/8/25.
  3. */
  4. let php = require('phpjs');
  5. function getServerIp() {
  6. let os = require('os');
  7. let ipv4;
  8. let net = os.networkInterfaces();
  9. let en0 = net.en0 || net.eth0;
  10. if (en0) {
  11. for (let i = 0; i < en0.length; i++) {
  12. if (en0[i].family.toLowerCase() === 'ipv4') {
  13. ipv4 = en0[i].address;
  14. }
  15. }
  16. }
  17. return ipv4 || '127.0.0.1';
  18. }
  19. function getClientIp(_req) {
  20. let ip = _req.headers['x-forwarded-for'] ||
  21. _req.connection.remoteAddress ||
  22. _req.socket && _req.socket.remoteAddress ||
  23. _req.connection.socket && _req.connection.socket.remoteAddress;
  24. let parts = ip && ip.split(':');
  25. if (parts && parts.length) {
  26. return parts[parts.length - 1];
  27. } else {
  28. return '';
  29. }
  30. }
  31. function checkIpRange(remote_ip, ip_array){
  32. //判断ip是否在白名单
  33. for (let i in ip_array) {
  34. let ip = ip_array[i];
  35. let ip_info = ip.split('/');
  36. let mask = ip_info[1] ? ip_info[1] : 32;
  37. let ip_mask = php.sprintf("%032b", php.ip2long(ip_info[0])).substr(0, mask);
  38. let remote_ip_mask = php.sprintf("%032b", php.ip2long(remote_ip)).substr(0, mask);
  39. if (ip_mask === remote_ip_mask) {
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. global['getServerIp'] = getServerIp;
  46. global['getClientIp'] = getClientIp;
  47. global['checkIpRange'] = checkIpRange;