简体   繁体   English

在socket.io中获取客户端的IPv4地址

[英]Get IPv4 Address of client in socket.io

When I log the 'socket' object during socket.on('connection'), I get the following information: _peername: { address: '::1', family: 'IPv6', port: 57535 } 当我在socket.on('connection')期间记录'socket'对象时,得到以下信息: _peername: { address: '::1', family: 'IPv6', port: 57535 }

How do I change the family to IPv4 during socket connection? 在套接字连接期间如何将系列更改为IPv4?

I was testing around and found that on the client if I use 我在周围测试,发现在客户端上是否使用

var socket = io('http://localhost:8000', { transports: ['websocket']});

the socket.handshake.address returns ::1 socket.handshake.address返回::1

If I use 如果我用

var socket = io('http://server_ip:8000', { transports: ['websocket']});

the socket.handshake.address return ::ffff:ipv4address socket.handshake.address返回::ffff:ipv4address

When you create an http instance, make sure you bind your connection to an IPv4 address. 创建http实例时,请确保将连接绑定到IPv4地址。 Example: 例:

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);

http.listen(8000, '0.0.0.0', function(){
    console.log('listening on *:8000');
});

That should do the trick. 这应该够了吧。 :) :)

This should listen on IPv4; 这应该在IPv4上侦听; Try it and let me know... 试试看,让我知道...

var net = require('net');

var server = net.createServer();
server.on('connection', handleConnection);

server.listen({
  host: 'localhost',
  port: 8000,
  exclusive: true
  }, function() {
     console.log('server listening to %j', server.address());
});

Output: 输出:

server listening to {"address":"127.0.0.1","family":"IPv4","port":8000}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM