node:net -如何从客户端套接字中检索端口和主机信息?

uxhixvfz  于 2023-05-22  发布在  Node.js
关注(0)|答案(1)|浏览(71)

我有一个TCP客户端

import net from 'node:net'

const tcpClient = new net.Socket()

tcpClient.connect(req.body.port, req.body.host, function() {
  console.log(`nodejs net client for TCP connection succesfully connected to port ${req.body.port} and host ${req.body.host}`);
})
// output: succesfully connected to port 4001 and host 192.168.10.45

客户端对象包含数据对象,它保存套接字是否打开的信息(data._readableState.closed),但我如何才能知道它连接到什么主机和端口?我到处都找不到。我这样检查tcpClient:

tcpRouter.get('/checkTCPConnection', (req, res) => {
  res.send(tcpClient)
})

而且没有TCPClient.remoteAddress之类的东西
如果我尝试:

tcpRouter.get('/checkTCPConnection', (req, res) => {
  res.send(tcpClient.remoteAddress)
})

我在终端(服务器)和无效的参数错误超时错误在浏览器。

c9x0cxw0

c9x0cxw01#

以下代码适用于我:

const { Socket } = require("net");

const client = new Socket();

client.on("connect", () => {
    console.log("Connected to", client.remotePort, client.remoteAddress)
});

client.connect(80, "example.com");

setTimeout(() => {
    console.log("Info:", client.remotePort, client.remoteAddress)
}, 1000);

输出:

Connected to 80 93.184.216.34
Info: 80 93.184.216.34

请记住,这是异步工作的。如果您这样做:

const { Socket } = require("net");

const client = new Socket();
client.connect(80, "example.com");

console.log("Info:", client.remotePort, client.remoteAddress);

你会得到:

Info: undefined undefined

.localAddress.localPort您的计算机网络信息。
.remoteAddress.remotePort(正如其名称所示)是您的对等体/目标的端口/地址。
从你的问题我不清楚,如果你想你的机器网络信息,或远程的。如果您需要信息,只需将.remote....local...交换即可
希望这对你有帮助。

相关问题