function_extend.js 1.4 KB

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