1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- /**
- * Created by benzhan on 15/8/25.
- */
- var php = require('phpjs');
- function getServerIp() {
- var os = require('os');
- var ipv4;
- var net = os.networkInterfaces();
- var en0 = net.en0 || net.eth0 || net.lo;
- for (var i = 0; i < en0.length; i++) {
- if (en0[i].family.toLowerCase() == 'ipv4') {
- ipv4 = en0[i].address;
- }
- }
- return ipv4;
- }
- function getClientIp(_req) {
- var ip = _req.headers['x-forwarded-for'] ||
- _req.connection.remoteAddress ||
- _req.socket && _req.socket.remoteAddress ||
- _req.connection.socket && _req.connection.socket.remoteAddress;
- var parts = ip && ip.split(':');
- if (parts && parts.length) {
- return parts[parts.length - 1];
- } else {
- return '';
- }
- }
- function checkIpRange(remote_ip, ip_array){
- //判断ip是否在白名单
- for (var i in ip_array) {
- var ip = ip_array[i];
- var ip_info = ip.split('/');
- var mask = ip_info[1] ? ip_info[1] : 32;
- var ip_mask = php.sprintf("%032b", php.ip2long(ip_info[0])).substr(0, mask);
- var remote_ip_mask = php.sprintf("%032b", php.ip2long(remote_ip)).substr(0, mask);
- if (ip_mask === remote_ip_mask) {
- return true;
- }
- }
- return false;
- }
- global['getServerIp'] = getServerIp;
- global['getClientIp'] = getClientIp;
- global['checkIpRange'] = checkIpRange;
|