nodejs获取客户机ip

/**
 * Created by chaozhou on 2015/11/24.
 */
var getIp = function(req){
    var ipStr = req.headers['x-forwarded-for'];        //F5
    if(ipStr){
        var ipArray = ipStr.split(",");
        if(ipArray.length > 1){             //如果获取到的为ip数组(用手机访问时,如果机房双线,可能获取到的为数组
            for(var i = 0; i < ipArray.length; i++){
                var ipNumArray = ipArray[i].split(".");
                var tmp = ipNumArray[0] + "." + ipNumArray[1];
                if(tmp == "192.168" || (ipNumArray[0] == "172" && ipNumArray[1] >= 16 && ipNumArray[1] <= 32) || ipNumArray[0] == "10"){    //排除特殊区间ip
                    continue;
                }
                return ipArray[i];
            }
        }
        return ipArray[0];
    }else{          //F5获取不到时
        return req.ip.substring(req.ip.lastIndexOf(":") + 1);
    }
};

exports.getIp = getIp;

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区