io.sockets.on('connection', function (socket) {
var socketId = socket.id;
var clientIp = socket.request.connection.remoteAddress;
console.log(clientIp);
});
function onSocketIoConnection(socket: SocketIO.Socket) {
// I usually create a custom kind of session object here.
// then I pass this session object to the onMessage and onDisconnect methods.
socket.on('message', (msg) => onMessage(...));
socket.once('disconnect', (reason) => onDisconnect(...));
}
最后,因为我们现在有了完整的输入,我们可以很容易地从套接字中检索 ip,而不需要猜测:
const ip = socket.conn.remoteAddress;
console.log(`client ip: ${ip}`);
// Current Client
const ip = socket.handshake.headers["x-forwarded-for"].split(",")[1].toString().substring(1, this.length);
// Server
const ip2 = socket.handshake.headers["x-forwarded-for"].split(",")[0].toString();
只是为了检查它是否有效,请访问 < a href = “ http://geoplugin.net/json.gsp? ip =”rel = “ nofollow norefrer”> geoplugin.net/json.gsp?ip=
一定要切换链接中的 IP 地址。在你这样做之后,它应该给你客户端的准确位置,这意味着它的工作。