Node.js net模块:如何从客户端Socket获取端口与主机信息?
如何获取Node.js TCP客户端已连接的主机和端口信息?
问题描述
我用Node.js的net模块创建了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) })
没有找到类似remoteAddress的属性;而尝试直接返回tcpClient.remoteAddress时:
tcpRouter.get('/checkTCPConnection', (req, res) => { res.send(tcpClient.remoteAddress) })
服务器终端出现超时错误,浏览器端提示无效参数错误。
解决方案
1. 使用正确的Socket属性获取远程地址和端口
Node.js的net.Socket客户端对象提供了直接获取已连接服务器地址的属性:
tcpClient.remoteAddress: 已连接的服务器IP地址tcpClient.remotePort: 已连接的服务器端口tcpClient.remoteFamily: 地址族(如IPv4/IPv6)
这些属性只有在连接成功建立后才会被赋值,未连接或断开时会返回undefined。
2. 避免直接返回Socket对象
直接用res.send(tcpClient)会触发超时,因为Socket对象包含大量循环引用的内部属性,无法被JSON正常序列化。应该只返回需要的属性:
tcpRouter.get('/checkTCPConnection', (req, res) => { res.send({ remoteHost: tcpClient.remoteAddress, remotePort: tcpClient.remotePort, isConnected: !tcpClient.destroyed // 更规范的连接状态判断方式 }); })
3. 提前保存连接信息(可选)
如果需要在连接断开后仍能获取历史连接信息,可以在连接成功的回调中保存地址和端口:
let connectedHost, connectedPort; 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}`); // 保存连接信息 connectedHost = tcpClient.remoteAddress; connectedPort = tcpClient.remotePort; }); // 接口中返回保存的信息或实时值 tcpRouter.get('/checkTCPConnection', (req, res) => { res.send({ remoteHost: connectedHost || tcpClient.remoteAddress, remotePort: connectedPort || tcpClient.remotePort, isConnected: !tcpClient.destroyed }); })
4. 处理未连接状态的情况
如果连接尚未建立或已断开,remoteAddress和remotePort会是undefined,可以在接口中添加状态判断,避免返回无效值:
tcpRouter.get('/checkTCPConnection', (req, res) => { if (tcpClient.destroyed) { return res.send({ status: 'disconnected' }); } if (!tcpClient.remoteAddress) { return res.send({ status: 'connecting' }); } res.send({ status: 'connected', remoteHost: tcpClient.remoteAddress, remotePort: tcpClient.remotePort }); })
内容的提问来源于stack exchange,提问作者DuchSuvaa
相关产品推荐
相关产品推荐

