others - socket.io获取客户端的IP地址

在Node.js服务器中使用socket.IO时,是否有一种简单的方法来获取传入连接的IP地址?

时间:


var io = require("socket.io").listen(server);

io.sockets.on("connection", function (socket) {
 var address = socket.handshake.address;
 console.log("New connection from" + address.address +":" + address.port);
}

对于1.0.4:


io.sockets.on('connection', function(socket) {
 var socketId = socket.id
 var clientIp = socket.request.connection.remoteAddress

 console.log(clientIp)
})


var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
 var endpoint = socket.manager.handshaken[socket.id].address;
 console.log('Client connected from: ' + endpoint.address +":" + endpoint.port);
});

对于最新的socket.io版本使用


socket.request.connection.remoteAddress

例如:


var socket = io.listen(server);
socket.on('connection', function(client){
 var client_ip_address = socket.request.connection.remoteAddress;
}

请注意,下面的代码返回服务器的IP,而不是客户端的IP,


var address = socket.handshake.address;
console.log("New connection from" + address.address +":" + address.port);

Socket.IO的版本0.7.7现在声明返回客户端的IP地址,我成功了:


var socket = io.listen(server);
socket.on('connection', function(client){
 var ip_address = client.connection.remoteAddress;
}

使用最新的1.0.6Socket.IO版本,并将应用程序部署到Heroku上,我使用,


var socketio = require('socket.io').listen(server);

socketio.on('connection', function(socket) {

 var sHeaders = socket.handshake.headers;
 console.info('[%s:%s] CONNECT', sHeaders['x-forwarded-for'], sHeaders['x-forwarded-port']);

}

由于socket.io 1.1.0,我使用:


io.on('connection', function(socket) {
 console.log('connection :', socket.request.connection._peername);
 // connection : { address: '192.168.1.86', family: 'IPv4', port: 52837 }
 }

另请参阅以下相关链接:engine.io问题

socket.request.connection.remoteAddress


var http = require('http')
 , io = require('socket.io');
io.listen(new http.Server().on('connection', function(sock) {
 console.log('Client connected from: ' + sock.remoteAddress);
}).listen(80));

在1.3.5中:

var clientIP = socket.handshake.headers.host ;

...