Get the client's IP address in socket.io

From: https://www.wentong.org/codex/question-2018081564702.html

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.

回答1:

Okay, as of 0.7.7 this is available, but not in the manner that lubar describes. I ended up needing to parse through some commit logs on git hub to figure this one out, but the following code does actually work for me now:

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);
});

回答2:

for 1.0.4:

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

  console.log(clientIp);
});

回答3:

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.

回答4:

For latest socket.io version use

socket.request.connection.remoteAddress

For example:

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

beware that the code below returns the Server‘s IP, not the Client‘s IP

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

回答5:

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

}

回答6:

This seems to work:

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);
});

回答7:

Since socket.io 1.1.0, I use :

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

Edit : Note that this is not part of the official API, and therefore not guaranteed to work in future releases of socket.io.

Also see this relevant link : engine.io issue

回答8:

Version 0.7.7 of Socket.IO now claims to return the client‘s IP address. I‘ve had success with:

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

回答9:

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

回答10:

From reading the socket.io source code it looks like the "listen" method takes arguments (server, options, fn) and if "server" is an instance of an HTTP/S server it will simply wrap it for you.

So you could presumably give it an empty server which listens for the ‘connection‘ event and handles the socket remoteAddress; however, things might be very difficult if you need to associate that address with an actual socket.io Socket object.

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

Might be easier to submit a patch to socket.io wherein their own Socket object is extended with the remoteAddress property assigned at connection time...

回答11:

Latest version works with:

console.log(socket.handshake.address);

回答12:

on socket.io 1.3.4 you have the following possibilities.

socket.handshake.address,

socket.conn.remoteAddress or

socket.request.client._peername.address

回答13:

use socket.request.connection.remoteAddress

回答14:

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.

回答15:

In socket.io 2.0: you can use:

socket.conn.transport.socket._socket.remoteAddress

works with transports: [‘websocket‘]

回答16:

In 1.3.5 :

var clientIP = socket.handshake.headers.host;

回答17:

socket.handshake.headers[‘x-forwarded-for‘].split(",")[0]

As of socket 3.1.2

Get the client's IP address in socket.io

原文地址:https://www.cnblogs.com/time-is-life/p/9598453.html

时间: 2024-10-10 12:10:57

Get the client's IP address in socket.io的相关文章

how to get the client's IP address

有时候总会有这种需求,今天我先起个头,汇总一下可以获取当前设备IP address的办法: 1. shell 正则 + python DATAIP = "ifconfig -a|awk \'/(cast)/ {print $2}\'|cut -f1-2 -d." data= subprocess.Popen(DATAIP,stdout=subprocess.PIPE,shell=True) tmp = data.stdout.read() _Real_IP = tmp.strip()

Python3 code to display hostname and IP address

OS: Windows 7 #!/usr/bin/env python3 # Python3 code to display hostname and # IP address # Importing socket library import socket # Function to display hostname and # IP address def get_Host_name_IP(): try: host_name = socket.gethostname() host_ip =

Nodejs 中使用Socket.io

安装socket.io npm install socket.io 或者在package.json文件中添加socket.io的依赖包,然后npm install安装所需模块. 在Express http服务器中使用socket.io 在 bin/www 文件中添加: var io = require('socket.io'); var socket = io.listen(server); socket.on('connection', function(client) { console.l

Socket.IO 概述

为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/SJQ. http://www.cnblogs.com/shijiaqi1066/p/3826251.html Socket.IO简述 Socket.IO用于浏览器与node.js之间实现实时通信.Socket.IO设计的目标是支持任何的浏览器,任何Mobile设备.支持主流的PC浏览器 (IE,Safari,Chrome,Firefox,Opera等),Mobile浏览器(iphone Safari/ipa

关于Socket.IO的知识点记录

最近因为项目的需要,开始学习nodejs,本着js的那点儿功底,nodejs学习起来还是挺快能上手的.随着深入学习,知道了express框架并那它写了一个小功能,作为一个php程序员哈,在express框架路由.模板渲染那里看到了Yii2的影子,所以便更加的亲切了.再接着便接触到了websocket,而今天谈论的socket.io 便是websocket的一个类库,说道这里了,我们先去了解下websocket和socket.io: 一  websocket WebSocket是html5新增加的

socket.io emit callback调用探秘

socket.io https://socket.io/ https://socket.io/docs/ What Socket.IO is Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. It consists of: a Node.js server: Source | API a Jav

Load Testing Socket.IO Web Applications and Infrastructure

转自:https://medium.com/better-programming/load-testing-socket-io-web-applications-and-infrastructure-3e96011898e0 关于artillery的一个实践 Are you shipping a scalable real-time back end? This article provides a tutorial for load testing your Socket.IO-based W

Linux Force DHCP Client (dhclient) to Renew IP Address

http://www.cyberciti.biz/faq/howto-linux-renew-dhcp-client-ip-address/‘m using Ubuntu Linux. How to force Linux to reacquire a new IP address from the DHCP server? What is the command in Linux equivalent to Windows’ “ipconfig /renew” command? You nee

Android Client 与 C# Server 的Socket通信

C# Socket Server 1.建立C# SocketServer 1 private void ServerStart() 2          { 3              //创建IPEndPoint 4              IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234); 5              //创建Socket实例 6              server_S