Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

How to get client IP address with WebSocket (websockets/ws) library in Node.js?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After a bit of messing around trying to figure out which one gives the client (web browser's) IP address, the answer is:

ws._socket.remoteAddress

Or if you have access to req via wss.on('connection', (ws, req) => {}):

req.connection.remoteAddress;

You can use this, for example, to GeoIP locate where the user is connecting from.

Edit:

If you're running Node behind an Nginx reverse proxy (or any other reverse proxy for that matter), you may need to use:

req.headers['x-forwarded-for'] || req.connection.remoteAddress

A note on security: If your Node server is available directly as well as through the reverse proxy, you might like to check the remoteAddress before trusting x-forwarded-for. The remote address should be your reverse proxy's IP. There's the odd chance someone could call your service directly and spoof x-forwarded-for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...