问题描述
我已经基于 NodeJS 的 Net 模块编写了一个服务器。如果我尝试使用网络套接字连接到它,它工作得非常好。但是,如果我尝试使用 nmap 对其进行扫描,则它无法写入套接字,从而出现 EPIPE
错误。
Error: write EPIPE
at afterWritedispatched (node:internal/stream_base_commons:160:15)
at writeGeneric (node:internal/stream_base_commons:151:3)
at Socket._writeGeneric (node:net:775:11)
at Socket._write (node:net:787:8)
at writeOrBuffer (node:internal/streams/writable:400:12)
at _write (node:internal/streams/writable:341:10)
at Socket.Writable.write (node:internal/streams/writable:345:10)
at Server.<anonymous> (/server.js:6:10)
at Server.emit (node:events:379:20)
at TCP.onconnection (node:net:1555:8)
Emitted 'error' event on Socket instance at:
at emitErrorNT (node:internal/streams/destroy:188:8)
at emitErrorCloseNT (node:internal/streams/destroy:153:3)
at processticksAndRejections (node:internal/process/task_queues:81:21) {
errno: -32,code: 'EPIPE',syscall: 'write'
}
我已将服务器代码简化为:
const net = require('net');
const server = net.createServer(socket => {
socket.write('Test');
});
server.listen(30);
nmap 输出只是说 30/tcp open tcpwrapped
。
我确定这与 nmap 连接到服务器的方式有关。但我就是不知道怎么做。
解决方法
您收到此错误的原因是 nmap 立即关闭了连接。当您的回调开始执行时,Node.js 已经收到了 RST 数据包并且它知道连接已关闭,因此它通过立即抛出错误来禁止写入 - 套接字是确保这一点的状态机。
作为一项规则,您应该随时准备好处理连接状态错误 - 可能,任何写入调用都可能失败。这与丢失数据包不同,因为在这种情况下,它们永远不会到达网络。