Get the client's IP address in socket.io

2019-01-04 07:10发布

When using socket.IO in a Node.js server, is there an easy way to get the IP address of an incoming connection? I know you can get it from a standard HTTP connection, but socket.io is a bit of a different beast.

17条回答
The star\"
2楼-- · 2019-01-04 07:48

If you use an other server as reverse proxy all of the mentioned fields will contain localhost. The easiest workaround is to add headers for ip/port in the proxy server.

Example for nginx: add this after your proxy_pass:

proxy_set_header  X-Real-IP $remote_addr;
proxy_set_header  X-Real-Port $remote_port;

This will make the headers available in the socket.io node server:

var ip = socket.handshake.headers["x-real-ip"];
var port = socket.handshake.headers["x-real-port"];

Note that the header is internally converted to lower case.

If you are connecting the node server directly to the client,

var ip = socket.conn.remoteAddress;

works with socket.io version 1.4.6 for me.

查看更多
祖国的老花朵
3楼-- · 2019-01-04 07:51

for 1.0.4:

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

  console.log(clientIp);
});
查看更多
【Aperson】
4楼-- · 2019-01-04 07:51

Using the latest 1.0.6 version of Socket.IO and have my app deployed on Heroku, I get the client IP and port using the headers into the socket handshake:

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']);

}
查看更多
虎瘦雄心在
5楼-- · 2019-01-04 07:52

Very easy. First put

io.sockets.on('connection', function (socket) {

console.log(socket);

You will see all fields of socket. then use CTRL+F and search the word address. Finally, when you find the field remoteAddress use dots to filter data. in my case it is

console.log(socket.conn.remoteAddress);
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-04 07:53
socket.handshake.headers['x-forwarded-for'].split(",")[0]

As of socket 3.1.2

查看更多
forever°为你锁心
7楼-- · 2019-01-04 07:54

I have found that within the socket.handshake.headers there is a forwarded for address which doesn't appear on my local machine. And I was able to get the remote address using:

socket.handshake.headers['x-forwarded-for']

This is in the server side and not client side.

查看更多
登录 后发表回答