node获取客户端ip问题
之前用的node版本是0.10.32
1.本机访问,拿到的ip是127.0.0.1
;
2.别的机器方式,拿到的ip就是别的机器的ip,假如我部署在局域网内,内网访问拿到的ip格式如下:192.168.1.xxx。
后来我node版本切到4.4.3的时候,出现了问题
1.本机访问,拿到的IP是 ::1
2.别的机器访问,拿到的ip是::ffff:192.168.0.2
这什么原因呢?代码如下:
function getClientIp (req) {
var ipAddress;
var forwardIpStr = req.headers['x-forwarded-for'];
if (forwardIpStr) {
var forwardIp = forwardIpStr.split(',');
ipAddress = forwardIp[0];
}
if (!ipAddress) {
ipAddress = req.connection.remoteAdress;
}
if (!ipAddress) {
ipAddress = req.socket.remoteAdress;
}
if (!ipAddress) {
if (req.connection.socket) {
ipAddress = req.connection.socket.remoteAdress;
}
else if (req.headers['remote_addr']) {
ipAddress = req.headers['remote_addr'];
}
else if (req.headers['client_ip']) {
ipAddress = req.headers['client_ip'];
}
else {
ipAddress = req.ip;
}
}
return ipAddress;
};
4 回复
从0.12.x(大概是,具体不记得了)开始,http.createServer().listen()的默认是ipv6,你可以改成.listen(port, “0.0.0.0”)强制指定为ipv4. 应该能解决你的问题。
net.Server.prototype.listen() will now try to bind to :: (IPv6) if the bind address is omitted, and use 0.0.0.0 (IPv4) as a fallback. 监听的是ipv6,文档里有提到:https://iojs.org/api/net.html#net_server_listen_port_hostname_backlog_callback