簡體   English   中英

Socket.io 給出相同的 ip 地址,無論從何處發生連接(使用 repl.it 托管)

[英]Socket.io gives same ip address no matter where the connection is happening from (hosting with repl.it)

這是一個更大的項目,但我設法將它濃縮成一個小程序。

我正在嘗試從 websocket 連接中獲取客戶端的 ip 地址。 我發現我可以使用 socket.handshake.address 但是當我在 repl.it 上運行它時,它總是說 ip 地址是 172.18.0.1 沒有我連接的地方。

索引.js

const express = require('express');


const http = require('http').createServer();
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);


app.get('/', (request, response) => {
    response.sendFile('/home/runner/basicSocketio/index.html');

    });


io.on('connection', (socket) => {
  io.emit("message", "hello client")

    socket.on('message', (message) => {
    console.log(socket.handshake.address)//always prints ::ffff:172.18.0.1
  })
})

索引.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-9">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src = "https://cdn.socket.io/socket.io-3.0.0.js"></script>

</head>
<body>
test
</body>
</html>

<script>


const socket = io();
socket.emit('message', "hi server");
socket.on('message', text => {
    console.log("recieved: " + text);
    

});

</script>

我不確定為什么會發生這種情況並且找不到任何解決方案,當我在本地運行它時它似乎工作正常。 我能做些什么來解決它?

172.18.0.1是 repl.it 的 HTML 服務器內部地址,因為它們為您提供index.html並且在那里您可以調用const socket = io()

要查看客戶端的真實 ip,請使用socket.handshake.headers['x-forwarded-for']表達式,如下所示:

 io.on('connection', (socket) => { io.emit('message', 'hello client') socket.on('message', (text) => { console.log(text) // console.log(socket.handshake.address) // Server serving index.html file IP address }) console.log('a client connected') console.log('client IP addr: ' + socket.handshake.headers['x-forwarded-for']) // (REAL) client IP })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM